Solved: How to open 2 mysql databases in php

All your question about php
Post Reply
mister_v
Posts: 188
Joined: Thu Mar 04, 2010 9:19 pm

Solved: How to open 2 mysql databases in php

Post by mister_v »

Hi,

I want to access 2 MYSQL databases from the same php script.
Without closing one and opening the other one.
I want to select queries from both databases at the same time.

Thanks
Last edited by mister_v on Wed Sep 26, 2012 1:48 pm, edited 1 time in total.
chris
Site Admin
Posts: 194
Joined: Mon Jul 21, 2008 9:52 am

Re: How to open 2 mysql databases in php

Post by chris »

You can add a 4th parameter in mysql_connect,
this will open a new separated connection.

Code: Select all

$dbconn1 = mysql_connect($hostname, $username, $password); 
$dconn2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbconn1);
mysql_select_db('database2', $dbconn2);

$result1=mysql_query("Select * FROM table",$dbconn1);
$line1=mysql_fetch_array($result1, MYSQL_NUM);

$result2=mysql_query("Select * FROM tableOtherDB",$dbconn2);
$line2=mysql_fetch_array($result2, MYSQL_NUM);

Perhaps a better way is to use mysqli
(You need to compile php with it)

Code: Select all

$mysqli1 = new mysqli($hostname, $username, $password, 'database1');
$mysqli2 = new mysqli($hostname, $username, $password, 'database2');

$result1=mysqli_query($mysqli1,"Select * FROM table");
$result2=mysqli_query($mysqli2,"Select * FROM tableOtherDB");

$line1=mysqli_fetch_array($result1, MYSQL_NUM);
$line2=mysqli_fetch_array($result2, MYSQL_NUM);
mister_v
Posts: 188
Joined: Thu Mar 04, 2010 9:19 pm

Re: How to open 2 mysql databases in php

Post by mister_v »

Thanks
Didn't know about the 4th parameter true.
Post Reply