Page 1 of 1

Insertind data into multiple tables using mysql_insert_id()

Posted: Tue Apr 06, 2004 7:13 am
by gerrymac
Hi

I am trying to insert data into two different tables using the mysql insert_id function. I have two tablse customer and custorder. When i run the following code instead of it getting the last inserted id from the customer table and inserting it into custorder table every value is put in as zero. So for example you would be presented with something that looks like this in the custorder table.

custid Bookdate
0 jan
0 Feb

etc.

Does anyone know what im doing wrong? Any help would be appreciated!
Below is the code:


$connection=mysql_connect("localhost","root","");


if (!$connection)
{
echo "Could not connect to MySQL server!";
exit;
}

$db=mysql_select_db("test2",$connection);

if (!$db)
{
echo "Could not change into the database";
exit;
}



$query = "insert into customer (name)
values('".$name."')";


$custid = mysql_insert_id();

# and insert the custorder details

$sql = "INSERT INTO custorder(custid, bookdate)
VALUES ( $custid , '".$date."')";

$result = mysql_query($sql);
}






mysql_query($query);


?>

Posted: Tue Apr 06, 2004 8:39 am
by liljester
you arent running the first query... you're just building the query string, then trying to get the mysql_insert_id. you have to actually run the first query, then get the id. something like this:

Code: Select all

$query = "INSERT INTO customer (name) VALUES ("$name");";
mysql_query($query);

$custid = mysql_insert_id();

$query = "INSERT INTO custorder (custid, bookdate) VALUES($custid, "$date");";
mysql_query($query);

Posted: Wed Apr 07, 2004 8:35 am
by gerrymac
Hi liljester, Yeah i see what you mean and have made the necessary changes. Its wotking fine now.