如何使用PHP使用多个数据库? [英] How to use multiple database using php?
问题描述
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);
?>
当我var_dump结果时,它返回false.这里有什么问题?谢谢.
When i var_dump the result, it return false. What is the problem here? Thank you.
推荐答案
如果两个数据库都位于同一mysql服务器上,并且您以唯一用户身份访问它们,则不需要两个连接.
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);
?>
尽管不需要2个连接,但是您可以使用相同的连接选择两个DB.
Altough there's no need for 2 connections, you can select both DB's using the same connection.
这篇关于如何使用PHP使用多个数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!