tags:

views:

29

answers:

4

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 calling mysql_connect repeatedly.

A: 

... if you want to provide the connection, pass it in the function call.

Fosco
We can't we have our code written such that all the query are done without pass in the handles. And then we switch the database behind the scenes between our db farms
erotsppa
How are you going to generate the link identifier if you don't connect to it?
Fosco
A: 

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.

m01
+3  A: 

Super ghetto version.

$defaultHandle;

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

function q($query){
    global $defaultHandle;
    return mysql_query($query,$defaultHandle);
}
smdrager
+1 for actually providing a usable solution, and calling it out for the hack it is.
kander
Can you override the mysql_query function? Otherwise this wouldn't work.
erotsppa
Why wouldn't it? You'd have to replace all calls to `mysql_query` in your existing codebase with calls to `q` instead, of course. But you'd have to do that regardless. **There is no way to make `mysql_query` do what you want,** there are only workarounds and hacks. This is a workaround, and a hackish one at that. But, it'll work.
Charles
A: 

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.

Charles