Tuesday, April 10, 2012

Insert into Multiple Tables using PHP with LAST_INSERT_ID()

Below is the code that I've tried but I can't seem to make the right tweaks to get the script to run properly.


$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')
 INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
 
 mysql_query($sql) or die (mysql_error());
 


Any help is much appreciated.



Answer:

You cannot execute two sql statements with mysql_query();
Use something like this:
$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')';
mysql_query($sql);

$clientId = mysql_insert_id();

$sql = 'INSERT INTO client_data (client_id, phone, zip, note) VALUES('.$clientId.', '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';

mysql_query($sql) or die (mysql_error());

No comments:

Post a Comment