简体   繁体   English

PHP函数中的MySQL连接会覆盖现有连接(其他数据库)-如何防止这种情况?

[英]MySQL connection within a PHP function overwrites existing connection (other database) - how can I prevent this?

We open a MySQL connection to host_ 1 at the beginning of our script. 我们打开我们的脚本的开头一个MySQL连接HOST_ 1。 Somewhere in between, we call a function that opens & closes a connection to host_ 2 (function retrieve_information_from_host_2). 介于两者之间,我们称之为打开和关闭,以HOST_ 2(功能retrieve_information_from_host_2)连接的功能。

Unfortunately, the code after the function call still uses the connection of the function ( host_2 ). 不幸的是, 函数调用代码 仍然使用 函数 的连接host_2 )。

We need it though to continue with the preceding connection host_ 1 . 我们需要它来继续前面的连接 host_ 1

<?php

function retrieve_information_from_host_2($host_2, $username_2, $password_2, $database_2) {
    $connection = mysql_connect($host_2, $username_2, $password_2);
    if($connection) {
        if(mysql_select_db($database_2)) {
            $sql = "SELECT * FROM table WHERE id = 1;";
            $erg = mysql_query($sql);
            $row = mysql_fetch_assoc($erg);

            return $row;
        }
        mysql_close($connection);
    }
}

if(mysql_connect($host_1, $username_1, $password_1)) {
    if(mysql_select_db($database_1)) {
        $sql = "SELECT * FROM table WHERE id = 1;";
        $erg = mysql_query($sql);
        $row = mysql_fetch_assoc($erg); # CORRECT - This returns data from host 1

        $row_host_2 = retrieve_information_from_host_2(); # CORRECT - This returns data from host 2

        $sql = "SELECT * FROM table WHERE id = 2;";
        $erg = mysql_query($sql);
        $row = mysql_fetch_assoc($erg); # WRONG - This returns data from host 2 instead of host 1
    }
    mysql_close();
}
?>

We have tried almost every combination by giving each connection a name 我们已经通过为每个连接命名来尝试几乎所有组合

$connection_1 = mysql_connect($host_1, $username_1, $password_1);
...
mysql_close($connection_1);

and closing them explicitly, etc. 并明确关闭它们,等等。

Nothing helps. 没有任何帮助。 Can someone give us a solution to this problem? 有人可以给我们解决这个问题的方法吗?

PS: We are bound to this approach (functions) and can't use classes. PS:我们受此方法(函数)的约束,不能使用类。

Thank you very much! 非常感谢你!

See manual for mysql_query for second parameter link_identifier (The MySQL connection) 有关第二个参数link_identifier,请参见mysql_query手册(MySQL连接)

If the link identifier is not specified, the last link opened by mysql_connect() is assumed. 如果未指定链接标识符,则假定使用mysql_connect()打开的最后一个链接。

You also should use mysqli instead of the old mysql. 您还应该使用mysqli而不是旧的mysql。

Try to pass your connection link identifier as second argument. 尝试将您的连接链接标识符作为第二个参数传递。

For example: 例如:

$connection1 = mysql_connect($host_1, $username_1, $password_1);
$connection2 = mysql_connect($host_2, $username_2, $password_2);
mysql_query('Query',$connection1);
mysql_query('Query',$connection2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM