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','abc@abc.com')"); //insert record to first table
$sql1 =mysql_query("INSERT INTO database2.table2 (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc@abc.com')"); //insert record to second table
please suggest me corrections for above code to insert data.
Simply connect to 1 database, insert new row, disconnect, connect to the other database, insert row into that one and disconnect.
Or you can use
$connect1
and$connect2
to refer to each of them separately and do the insertion parallely.EDIT: Btw you can select the database with the 4'th parameter of
mysql_connect
, no need to usemysql_select_db
And very important, you should write
mysqli
notmysql
. Becausemysql
functions are not going to be supported for much longer.Well, that's how i do it...
1 - connect --> that you are doing right 2 - check for errors 3 - USE a database (1) you want to put data in (and not 'SELECT') 4 - check for errors 5 - now INSERT items into the database THAT IS BEING USED - that is (1) 6 - check for errors 7 - USE the other database (2) 8 - check for errors 9 - INSERT the data into (2) - because that is the one in use now 10 - check for errors
Yes, be paranoid :P Hope this helps
Try the following code:
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.
Well, if there's a pattern in db names, tables and queries are exactly the same, you can use a loop:
However, using mysql_* is strongly NOT recommended, as it is deprecated from the last stable PHP release and is considered unsafe. Use PDO or MySQLi instead. PHP's official site suggests the article "Choosing an API": http://www.php.net/manual/en/mysqlinfo.api.choosing.php
first create two database connections
Then select the database for each connection.
Then pass in a second argument for
mysql_query
which is the respective connection for the query.