views:

37

answers:

2

I have 2 functions, the function get_user_info() which connects to a db called 'users', and another, called print_info() which connects to a db called 'blah'. I call get_user_info() inside print_info(), so it can retrieve the information. They connect to 2 different databases and make 2 different connections, i use another function to connect to the db which is called connect_db($dbidhere). When I call get_user_info() it like cancels out the other connection, and I have to reconnect to the db called 'blah' after I call get_user_info(). Is there a way to have a private connection just for inside a function and doesnt cancel out the other connection?

function get_user_info() {
connect_db($db1);
$query = 'blah blah';
$row = mysql_fetch_array($query);
echo $row['cool'];
}

function print_info() {
connect_db($db2);
$query = 'blah blah again';
get_user_info(); // Here is where it cancels out the 'connect_db($db2)' and replaces it with get_user_info connection
}
+1  A: 

It doesn't cancel it out, you ask it to replace the default connection.

You probably want to take a look at how you can use the returned value from mysql_connect as an optional link identifier argument to most functions like mysql_query that talks to the database.

Edit: Assuming that you aren't already, it is hard to say as you have omitted both the mysql_query() and the mysql_connect() calls.

Fredrik
just realized it was using the same variable to connect so im assuming thats what replaced it, thanks bro!
David
@David: I hope you solve it then.
Fredrik
+1  A: 

It's important that you pass your database handler as the second argument to mysql_query();

$result = mysql_query('select ...', $db1); OR
$result = mysql_query('select ...', $db2);

<?php

$DB1 = mysql_connect('localhost', 'user', 'pass') or die('Could not connect to localhost db');
mysql_select_db('foo', $db1);

$DB2 = mysql_connect('192.168.0.2', 'user', 'pass') or die('Could not connect to 192.168.0.2 db');
mysql_select_db('bar', $db2);

function get_user_info($id){

  // access to DB1
  global $DB1;

  // try something like:
  if($result = mysql_query("select user.* from user id = {$id}", $DB1)){
    $user = mysql_fetch_assoc($result);
    echo $user['name'];
  }

}

function print_info(){

  // access to DB2
  global $DB2

  // try something like:
  if($result = mysql_query("select user_id from foo where bar = 'zim'", $DB2)){
    $foo = mysql_fetch_assoc($result);
  }

  get_user_info($foo['user_id']);

}

?>
macek