yuli chika
yuli chika

Reputation: 9221

PHP multi database connect

<?
    $db1 = mysql_connect("localhost","root","root") or dir("can not connect Mysql Server");
    mysql_select_db("1",$db1) or dir("Can not connect to the MySQL Server.");

    $db2 = mysql_connect("localhost","root","root") or dir("can not connect Mysql Server");
    mysql_select_db("2",$db2) or dir("Can not connect to the MySQL Server.");
?>

$result = mysql_query("SELECT * FROM db1.tags WHERE db1.catalog='fresh tag' ");

If I connect from a multi database, how to make a MySQL query from db1?

Upvotes: 3

Views: 1332

Answers (7)

David
David

Reputation: 1

//get my conn
include "../../database.php";
//put data in
//get data
if($_GET['attribute']!=''){
    //prepare
    $stmt=$conn->prepare('INSERT INTO databasetablename (attribute) VALUES (?)');
    //bind
    $stmt->bind_param('s',$_GET['attribute']);
    //execute
    $stmt->execute();
    $stmt->close();
}

    //print data out
    $res=$conn->query("SELECT attribute FROM databasetablename");
    if($res){
        while($hold = mysqli_fetch_array($res,MYSQL_ASSOC)){
            $record[]=$hold;
            echo $hold['attribute'];
        }
    }
    echo '<hr/>';
    //print out
        foreach($record as $cur){
            echo $cur['attribute'].<br/>;
        }

Upvotes: 0

Pradeep Singh
Pradeep Singh

Reputation: 3634

Use

mysql_query($query, $db1);

or

mysql_select_db();

Upvotes: 1

Luis Alvarado
Luis Alvarado

Reputation: 9406

If they are both in localhost you do not need to connect 2 times. you could simply do something like this:

SELECT * FROM db2.tags WHERE id IN(SELECT id FROM db1.tags WHERE id=1)

This way you can compare between both Databases without making two connections.

Now if you do not have both in the same place then you can do something like this:

mysql_select_db(db1);
$db1Result = mysql_query("SELECT * FROM db1.tags WHERE id=1");
mysql_select_db(db2);
$db2Result = mysql_query("SELECT * FROM db2.tags WHERE id=1");

And after that compare the results from $db1Result with the ones from $db2Result.

Upvotes: 1

Paul Schreiber
Paul Schreiber

Reputation: 12599

See the mysql_query documentation. You just pass in link_identifier as the second parameter.

$result = mysql_query("SELECT * FROM db1.tags WHERE db1.catalog='fresh tag'", $db1);

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101614

The second parameter of mysql_query is the connection resource. it will query against that connection.

Upvotes: 2

Darryl E. Clarke
Darryl E. Clarke

Reputation: 7647

Specify it in the query.

$result = mysql_query($query, $db1);

If the second parameter ($db1) is omitted, it will use the last defined resource ($db2)

Upvotes: 8

Pekka
Pekka

Reputation: 449823

Look in the manual.

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

Like you already do for mysql_select_db(), you can specify the connection as the second parameter.

Upvotes: 2

Related Questions