How do you insert data into two tables?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: How do you insert data into two tables?

Post by klevis miho »

Can you please give me a simple transaction template with php?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: How do you insert data into two tables?

Post by Christopher »

All the basic code you need is provided in the manual pages for mysql_connect() and mysql_query(). You need to get that code working first before you can use transactions. Once you have that code working then you just make the queries I provided in my previous post before and after your multiple inserts.
(#10850)
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: How do you insert data into two tables?

Post by klevis miho »

OK I did this:

Code: Select all

mysql_query("START TRANSACTION");
$sql1 = "INSERT INTO domain1(domain, user_id) VALUES('$domain', $user_id)";
$query1 = mysql_query($sql1);
$dom_id = mysql_insert_id($query1);
$sql2 = "INSERT INTO domain2(domain_id, user_id) VALUES($dom_id, $user_id)";
$query2 = mysql_query($sql2);
if($query1 && $query2) {
	echo 'Domain inserted successfully.';
	mysql_query("COMMIT");
} else {
	mysql_query("ROLLBACK");
}
But it does not insert anything, do you know what I am doing wrong?
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: How do you insert data into two tables?

Post by klevis miho »

Nevermind, I was doing this:
$dom_id = mysql_insert_id($query1);

wrong.


Thank you for your help, it was easier than I thought :)
Post Reply