I've read in PDO manual that to close connection you should use the following:
$connection = null;
However, Some people suggested that since PHP 5.3 has a new GC, the following should be used:
unset($connection);
I need to know once and for all, which one is preferred, or are they the same?
They do the same thing. Unsetting the $pdo handle and setting it null both close the connection.
You can test this for yourself. Run the following script in one window, and in a second window open the MySQL client and run SHOW PROCESSLIST every couple of seconds to see when the connection disappears.
<?php
$pdo = new PDO(..);
sleep(10);
unset($pdo);
echo "pdo unset!\n";
sleep(10);
Then change unset($pdo) to $pdo=null; and run the test again.
<?php
$pdo = new PDO(..);
sleep(10);
$pdo = null;
echo "pdo set null!\n";
sleep(10);
The extra sleep() at the end is there to give you a moment to see that the connection has dropped, before the PHP script terminates (which would drop the connection anyway).
I stumbled with this. I have a PDO object that spans setup and teardown, and I can't find where there must be a remaining reference, as setting $pdo to null did not resolve the problem.
User Contributed Notes in http://php.net/manual/en/pdo.connections.php discusses the problem of delayed closure. Here they suggest killing the current connection:
$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());');
$pdo = null;
This is for postgres. For mysql I have used:
$pdo->query('KILL CONNECTION CONNECTION_ID();');
using
$pdo = null; //is an assignment to null; the variable still declared in the memory.
but
unset($pdo); // will call the function to distroy also the adress "#" pointed by the variable.
so using unset is prefered.
Just don't bother with closing at all. PHP will close it for you all right.
Note that of course your application have to be sanely designed, without the need of reconnecting to different databases at a rate of machine-gun. And even in latter case, the method you are using to close would be the least problem. You are barking wrongest tree ever. Work the number of connections, not the way you are closing them.
Related
PHP+MySQL, What would happen when calling mysql_connect twice, like that:
$link = mysql_connect($server, $user, $pass);
$link = mysql_connect($server, $user, $pass);
PHP doesn't seem to generate any notice. Is the second line ignored or the new connection is established (if so, does that auto-close the previous connection) ?
I know, those situations shouldn't happen in the first place.
I know its an old question, but i was wondering the same thing myself.
So i did a test to see if php would actually ignore one connection, or open a new connection (which would be bad as it would probably put some additional load on the database).
<?
$test1 = mysqli_connect("127.0.0.1","root","pass","test_db");
$test2 = mysqli_connect("127.0.0.1","root","pass","test_db");
print "<pre>";
print_r($test1);
print_r($test2);
print "</pre>";
?>
The above will output a [thread_id].
By comparing the two ids, i found that they were not similar, and therefore i must assume that 2 connections are now open.
I was also looking for the answer. Tnx to ComFreek I got to solve my problem. I was facing the error
mysql err 2014: Commands out of sync; you can't run this command now
which is because of executing new query in middle of fetching another one in the connection. Then I was wondering if the mysqli_connect always returns a new connection or it returns an opened one if exists. About parameter 'new_link' the documentation of the deprecated "mysql_connect" says (http://php.net/manual/en/function.mysql-connect.php) :
new_link
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link
identifier of the already opened link will be returned. The new_link
parameter modifies this behavior and makes mysql_connect() always open
a new link, even if mysql_connect() was called before with the same
parameters. In SQL safe mode, this parameter is ignored.
but the documentation of the newer class "mysqli::__construct" says (http://php.net/manual/en/mysqli.construct.php):
Opens a connection to the MySQL Server.
which means it always returns a new connection so I checked it out and did the new query (the one in middle) with a new connection and it's fixed.
I have a normal website. It uses PHP to call a MySQL table. To save on typing it out all the time, I include() a connect.php file which connects to the database for me on every page. The website keeps getting a "mysql too many connections" error. Is it a bad idea to connect at the start of a page like this?
Should I create a new connection each time a PHP script needs it, then close that connection with mysql_close after that script is done? I had avoided doing as it would add repeated lines of code to the website but I'm wondering if that's what's causing the issue?
So at the moment my code is similar to this:
<?php
include("connect.php"); //connects to database using mysql_connect() function
...
PHP script that calls mysql
...
another PHP script that calls mysql
?>
Should I change it to something like this?
<?php
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
PHP code that calls mysql
mysql_close();
...
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
more PHP code that calls mysql
mysql_close();
?>
You should avoid making new connections to your database, as long as possible.
Making connection to database is a slow and expensive process. Having an opened connection consume few resources.
By the way, stop using mysql_* functions. Use mysqli_* or PDO.
Should I create a new connection each time a PHP script needs it [...] ?
Yes, that makes most sense, especially if not every page needs a mysql connection.
In PHP this works by setting up the database credentials in the php.ini file and you can just call mysql_select_db and it will automatically connect to the configured database if no connection exists so far.
If you write new code, encapsulate the database connection in an object of it's own so that you can more fine-grained control when to connect to the database.
Modern frameworks like for example Silex allow you to lazy load such central components (Services), so you have configured them and can make use of them when you need them but you don't need to worry about the resources (like the connection limit in your example).
[...] close that connection with mysql_close after that script is done?
You don't need that normally because PHP does this for you.
I do not think there is anything really wrong with this style of coding. It all depends on what kind of app you are writing. Just make sure you check your scripts well and get ride of any errors, you should be fine.
This is what i usually do
<?php session_start(); include "inc/config.php";
//require_once('chartz/lib/idiorm.php');
if ($_SESSION["login1"]== "Superadmin" or $_SESSION["login1"]== "User" or $_SESSION["login1"]=="Administrator")
{
$snames = $_SESSION["name1"];
$id = $_SESSION["id1"];
$stype = $_SESSION["login1"];
$stokperm = $_SESSION['stokperm'];
$navtype = $_GET['nav'];
include("inc/ps_pagination.php");
}
else
{
header ("location: ../../../index.php");
}
?>
Am not saying its the very best way out there, we are all still learnig...
I also thing you should take the advice of blue112 very seriously. Most of my apps are writing in the old fashion way, but Use mysqli_* or PDO is the way to go.
Do I need to explicitly kill and/or close a mysqli connection at the end of a script. At the moment, I do neither, and it works, but I don't have much load.
I've heard that there is connection pooling, and mysqli connections are re-used... do I need to close the connection then at all?
You should always close your connections at the end of the main script. If you uses some php5 and object to handle your DB just think about using __destruct() to automatically close it
http://php.net/manual/en/language.oop5.decon.php
No it is not necessary to close a mysql connection at the end of a script. PHP does it automatically.
it is not necessary but generally that's good practice. I personally, when wish to boost error-checking mechanism, you $con->close() for almost each function. e.g:
if($stmt = $db->prepare($statment))
{
if($db->bind_param($str, $param1, $param2))
{
// the rest of the code and error checking
}
else
}
$db->close();
}
}
else
{
$db->close();
}
This makes OOP necessary. Since you can simply write function doing this automatically with many other security checks added. codeIgniter as a framework has nice DB connectors whith superb security at a basic general level.
Currently, I'm opening a database connection in my app's initialization. It's a fairly small app, PHP if that's relevant.
Should I be connecting to the database, making calls, then closing and repeating this process for each database function I write?
For example, I have the following function which grabs the $db variable from my app's initialization.
function get_all_sections()
{
global $db;
$sql = 'select * from sections';
if (!$db->executeSQL($sql, $result))
{
throw new Exception($db->getDatabaseError());
exit();
}
$sections = array();
for ($i = 0; $i < $db->numberOfRows($result); $i++)
{
$sections[] = new Section($db->fetchArray($result, MYSQLI_ASSOC));
}
return $sections;
}
Would it be better if I opened the connection then closed it after I fetched the rows? That seems like a lot of connections that are opened and closed.
If you have connection pooling on (http://en.wikipedia.org/wiki/Connection_pool) its ok to be grabbing a new connection when you need it. HOWEVER, I'd say to be in the habit of treating any resource as "limited" and if you open the db handle keep it around for as long as possible.
Connecting to the database takes a finite amount of time. It's negligible when connecting over a domain socket or named pipe, but it can be much larger if over a network connection, or worse yet, the open Internet. Leave it connected for the life of the request at least.
Use mysql_pconnect for connection pooling, and close at the end of each operation. The thread won't really close, and the thread will be re-used. This way its both safe and efficient.
Since PHP MySQL connections are fairly light-weight, you are probably OK opening and closing the connection when needed. The same is not true of other database connections, such as connecting to SQL Server, which has rather heavy connections.
In all cases, however, do whatever makes the most sense in terms of maintainability/logic/dependencies. Then, if you find you are feeling a measurable slowdown, you can optimize those areas that need the speed-boost.
When in doubt, follow the golden rule: Don't optimize prematurely.
The simplest solution would be to use mysql_pconnect() - see here
This way if the connection is already open it will use it instead of creating a new one. If it's not it will connect again
$con = mysql_connect("localhost:".$LOCAL_DB_PORT, $LOCAL_DB_USER, $LOCAL_DB_PASS);
mysql_select_db("hr", $con);
mysql_query("set names utf8", $con);
while(true)
{
do_stuff($con);
sleep(50);
}
If connection timesout in 50 seconds,will $con still work?
If the connection times out, it won't work.
To answer the question from the comment, to cope with the problem, refer to php.net manual page for mysql_connect() which says:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
so if you want to make sure you always have an open connection, just try to open a new one with the same arguments after the code you substituted with sleep() is done executing.
Simple answer: why don't you try it and see?
I believe codeburger is correct: if the MySQL connection times out, then it's gone. You could use a persistent connection with mysql_pconnect. You will need to call that function after sleep each time but it will use an existing connection, saving overhead.