How to use multiple databases using php?

I read a few questions on the internet, including this one overflowing https://stackoverflow.com/a/312624/2129 , but none of them work 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 returns false. What is the problem? Thank.

+3
source share
3 answers

You do not need two connections if both databases are located on the same mysql server and you access them as a unique user.

You also do not need to choose a database.
Just use the database name as a prefix when specifying 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 is in your code: there is only one active database, it should work as follows:

<?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);

?>

, , .

+6

, . , true

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

Do not use mysql connector, use mysqli. It is more secure than mysql.

the code will be.

$conn1  = new mysqli("localhost","user","password","db1");
$conn2  = new mysqli("localhost","user","password","db2");

$query1 = "select * from table1";
$query2 = "select * from table2";

echo $query1 . "<br />";
echo $query2 . "<br />";

$rs1 = $conn1->query($query1);
$rs2 = $conn2->query($query1);

Also check if the request is correct. In most cases, an error occurs in the request, and not in the syntax.

+2
source

Source: https://habr.com/ru/post/1774438/


All Articles