如何将数据插入2数据库?

时间:2019-04-22 07:28:01

标签: php mysqli

我试图将数据插入到不同数据库中的2个表中。但是我无法连接到第二个数据库。

$con1 = mysqli_connect("localhost","root","","db1");

$sql_1 = "insert into enquiry(name,email,phone,subject,message,service_category) values('aa','aa@gg.com','12344','xxx','ddd','ddd')";

$res_1 = mysqli_query($con1,$sql_1);

$con = mysqli_connect("localhost","root","","db2");

$sql = "insert into customers(cname,cphone,cemail) values('$name','$phone','$email')";

$res = mysqli_query($con,$sql);

1 个答案:

答案 0 :(得分:2)

您可以通过一个连接完成此操作

$db = new mysqli($host,$user,$pass);

选择数据库时使用此

mysqli_select_db('DB_NAME', $db);

您编码

$con1 = mysqli_connect("localhost","username","password");
/* For the DB1 */
mysqli_select_db('DB_NAME1', $con1);
$sql_1 = "insert into 
enquiry(name,email,phone,subject,message,service_category) 
values('aa','aa@gg.com','12344','xxx','ddd','ddd')";
$res_1 = mysqli_query($con1,$sql_1);

/* For the DB2 */
mysqli_select_db('DB_NAME2', $con1);
$sql = "insert into customers(cname,cphone,cemail) 
values('$name','$phone','$email')";
$res = mysqli_query($con1,$sql);