Insertind data into multiple tables using mysql_insert_id()

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

Post Reply
gerrymac
Forum Newbie
Posts: 15
Joined: Sat Mar 13, 2004 6:19 am

Insertind data into multiple tables using mysql_insert_id()

Post 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);


?>
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post 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);
gerrymac
Forum Newbie
Posts: 15
Joined: Sat Mar 13, 2004 6:19 am

Post by gerrymac »

Hi liljester, Yeah i see what you mean and have made the necessary changes. Its wotking fine now.
Post Reply