How to insert data in two different tables of two different database in php

M Gaidhane picture M Gaidhane · Jul 22, 2013 · Viewed 7.5k times · Source

I have to insert data in two different database's table. I have created database1 and table1 for database1, also i have created database2 and table2 for database2.

For inserting data i have written code,

$connect = mysql_connect("localhost","root",""); //database connection

mysql_select_db("database1",$connect); // select database1 
mysql_select_db("database2",$connect); // select database2 

$sql = mysql_query("INSERT INTO database1.table1 (contact_first, contact_last, contact_email) VALUES('abc','xyz','[email protected]')"); //insert record to first table
$sql1 =mysql_query("INSERT INTO database2.table2 (contact_first, contact_last, contact_email) VALUES('abc','xyz','[email protected]')"); //insert record to second table

please suggest me corrections for above code to insert data.

Answer

Dhaval Bharadva picture Dhaval Bharadva · Jul 22, 2013

Try the following code:

$connect1 = mysql_connect("localhost","root","");
mysql_select_db("database1", $connect1);
$res1 = mysql_query("query",$connect1);

$connect2 = mysql_connect("localhost","root","",true);
mysql_select_db("database2", $connect2);
$res2 = mysql_query("query",$connect2);  

Note: So mysql_connect has another optional boolean parameter which indicates whether a link will be created or not. as we connect to the $connect2 with this optional parameter set to 'true', so both link will remain live.