Reputation: 113
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.
Upvotes: 2
Views: 1628
Reputation: 1398
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.
Upvotes: 0
Reputation: 1205
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.
Upvotes: 3