1
votes

I am using pdo method to connect to the MySQL databases via PHP.

Here are the steps that my page is written to execute. 1) open connection 2) run queries 1 3) run queries 2 4) run queries 3 5) close connection.

Now if I want to redirect a user to a different page using "header('Location new_page.php')" function after step 3 will the connection to the database be auto close since the user left the page? or do I need to close the connection manually before the transfer happens?

thanks

3
Google found many results on the subject. The answer is yes, it will. Google search term used "does mysql connection automatically close after redirect?"Funk Forty Niner
if your script not finished after header with die or exit, then not... step 4 will be execute too...vp_arth
also if you use PDO::ATTR_PERSISTENT, then your connection not closed after php execution end, and will reused by next pdo connectsvp_arth
PHP cleans up when a script terminates, which also closes any open db connections, closes open files, blah blah blah.Marc B

3 Answers

3
votes

You don't have to do it , the connection closes automatically at the end of the script.

From the PHP Docs ...

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

This is common for PDO too.

Also, this ...

with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

To answer your question..

Now if I want to redirect a user to a different page using "header('Location new_page.php')" function after step 3 will the connection to the database be auto close since the user left the page? or do I need to close the connection manually before the transfer happens?

Whenever, you do a header , use an exit or a die to end the script.

die(header("location:somepage.php"));

or

header("location:somepage.php");
exit;
2
votes

Yes, the connection will be closed after the PHP execution finished of that page. In other words, at the end of page loading the connections will be closed.

1
votes

No, header calling don't stops the script execution

Explain:

<?php

//1) open connection 
//2) run queries 1 
//3) run queries 2 
header('Location: /');
//script execution continuous here
//4) run queries 3 
exit();// here php close all your connections
//5) run queries 4 //Unreachable code
//6) close connection.