views:

101

answers:

1

Hi,

for a project I need to open a Mysql connection, close it and let old legacy code run after that. The legacy code have it's own connection, and just call mysql_query($sql) without the resource parameter.

How can I handle this? Can I set a Mysql connexion as the global one? Must I re-execute the mysql_connect() statement? The legacy code can't be refactored just now.

Here a short demo

<?php

function show()
{
    $a = mysql_fetch_array(mysql_query('select database()'));
    echo $a[0] . "<br>";
}

$conn = mysql_connect('localhost', 'root', '', TRUE);
mysql_select_db('dredd');
show();

mysql_connect('localhost', 'root', '', TRUE);
mysql_select_db('afup');
show();
mysql_close();

$a = mysql_fetch_array(mysql_query('select database()', $conn));
echo $a[0] . "<br>";

show();

The first select is ok, the second two, the third is ok because it have the ressource, but the fourth broke ("Access denied for user 'ODBC'@'localhost' (using password: NO)").

Regards, Cédric

+5  A: 

If you don't specify the connection it will use the last created one, so it should be ok if you close the other connection first, e.g.

//open your db connection
$conn1 = mysql_connect();
mysql_query($sql, $conn1);
mysql_close($conn1);

//open legacy code's db connection
$conn = mysql_connect();
//run legacy code

If you are having problems it might be easier to use PDO or mysqli for the second connection, because then you know they are definately separate without modifying the legacy code.

Tom Haigh
My db connection is for a error catch up system, so the legacy code is interrupted, my code run, and the legacy code continue. But your idea is very good, thanks! I try it asap.
Cédric Girard