3

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.

Community
  • 1
  • 1
cyberfly
  • 5,568
  • 8
  • 50
  • 67

3 Answers3

6

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.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
2

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());
cyberfly
  • 5,568
  • 8
  • 50
  • 67
2

Don't use mysql connector, use mysqli. It is more secure compared to mysql.

the code would 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 the query is correct. Most of the times the error is in the query and not the syntax.

Chaitannya
  • 936
  • 1
  • 7
  • 16
  • If you're going to recommend ditching one connection option in favour of another, then it really should be PDO_MySql – Phil Nov 12 '10 at 03:56