Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple database using php?

Tags:

php

mysql

I have read multiple question in the internet including this stackoverflow question but none of them working for me. Here is my code:

<?php

$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
$conn2 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());

mysql_select_db("asteriskcdrdb",$conn1);
mysql_select_db("pj8v2",$conn2);

$query = "SELECT * FROM cdr";
$result = mysql_query($query,$conn1);

var_dump($result);

$query2 = "SELECT * FROM tb_did_avalaible";
$result2 = mysql_query($query2,$conn2);

var_dump($result2);

?>

When i var_dump the result, it return false. What is the problem here? Thank you.

like image 599
cyberfly Avatar asked Apr 30 '26 06:04

cyberfly


2 Answers

You dont need two connections, if both databases are located on the same mysql-server and you access them both as unique user.

You also don't need to select a DB.
Just use the database-name as prefix when specifying the tables:

<?php

mysql_connect("localhost","root","pass") or die(mysql_error());

$query = "SELECT * FROM asteriskcdrdb.cdr";
$result = mysql_query($query)or die(mysql_error());
var_dump($result);

$query2 = "SELECT * FROM pj8v2.tb_did_avalaible";
$result2 = mysql_query($query2)or die(mysql_error());
var_dump($result2);

?>

The real problem in your code is: there can only be one active DB, it should work this way:

<?php

$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());   
$conn2 = mysql_connect("localhost","root","passw0rd",true) or die(mysql_error());

mysql_select_db("asteriskcdrdb",$conn1);
$query = "SELECT * FROM cdr";
$result = mysql_query($query,$conn1);

var_dump($result);


mysql_select_db("pj8v2",$conn2);
$query2 = "SELECT * FROM tb_did_avalaible";
$result2 = mysql_query($query2,$conn2);

var_dump($result2);

?>

Altough there's no need for 2 connections, you can select both DB's using the same connection.

like image 194
Dr.Molle Avatar answered May 02 '26 19:05

Dr.Molle


Sorry i just figure out the problem. If using same connection parameter, must add true in the connect parameter

$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
$conn2 = mysql_connect("localhost","root","passw0rd",true) or die(mysql_error());
like image 31
cyberfly Avatar answered May 02 '26 19:05

cyberfly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!