我在互联网上阅读了多个问题,包括stackoverflow question,但没有一个问题适合我。这是我的代码:
<?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);
?>
当我var_dump结果时,它返回false。这里有什么问题?谢谢。
答案 0 :(得分:6)
如果两个数据库都位于同一个mysql-server上,并且您作为唯一用户访问它们,则不需要两个连接。
您也无需选择数据库 在指定表时只需使用database-name作为前缀:
<?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);
?>
代码中的真正问题是:只能有一个活动数据库,它应该以这种方式工作:
<?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);
?>
尽管不需要2个连接,但您可以使用相同的连接选择两个DB。
答案 1 :(得分:2)
抱歉,我只是弄清楚了问题。如果使用相同的连接参数,则必须在connect参数中添加true
$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
$conn2 = mysql_connect("localhost","root","passw0rd",true) or die(mysql_error());
答案 2 :(得分:2)
不要使用mysql连接器,请使用mysqli。与mysql相比,它更安全。
代码将是。
$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);
同时检查查询是否正确。大多数情况下,错误在查询中,而不是语法。