开发者

Is there a way to set the default database handle with mysql_query?

开发者 https://www.devze.com 2023-01-09 15:42 出处:网络
Is there a way to set the default database handle with mysql_query? So I know that mysql_query can be called without a sql handle but then it will basically use whatever handle you got from the last m

Is there a way to set the default database handle with mysql_query? So I know that mysql_query can be called without a sql handle but then it will basically use whatever handle you got from the last mysql_connect. What if I wanted to set that default handle myself, how do I do it?


I just want to make it clear that we have all our code written without the handler passed in. We can't change those. We have some code behind the scenes that changes the database between different database clusters. We want to be able to switch between the database without c开发者_运维问答alling mysql_connect repeatedly.


Super ghetto version.

$defaultHandle;

function SetDefaultHandle($handle){
    global $defaultHandle;
    $defaultHandle = $handle;
}

function q($query){
    global $defaultHandle;
    return mysql_query($query,$defaultHandle);
}


Try this:

$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_query($query, $dbc);

From manual:

resource mysql_query ( string $query [, resource $link_identifier ] )

link_identifier - The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.


Rather than pointing you at the manual, which you certainly have read by now based off your question...

You can't do this with the mysql extension.

The magic "pick the last handle opened" behavior is defined by the extension itself. There's nothing you can do to change this behavior.

The behavior you've asked for will require custom code, almost certainly replacing every call to every function with an appropriate wrapper that picks the correct database handle for your load balancing situation.


If you want to provide the connection you can pass it in the function call as the second argument. See documentation of mysql_query for further details.

0

精彩评论

暂无评论...
验证码 换一张
取 消