Jump to content

Archived

This topic is now archived and is closed to further replies.

pseudomega

Can I retreive an auto increment value on the fly?

Recommended Posts

This is my current INSERT statement which uses POST'ed data from an HTML form:
[code]$store = "INSERT INTO stores (store_type, store_state, store_zip, store_phone, store_status, store_comments) " .
"VALUES ('$store_type', '$store_state', '$store_zip', '$store_phone', '$store_status', '$store_comments')";

$owner = "INSERT INTO owners (owner_name) " .
"VALUES ('$owner_name')";[/code]

The 'owners' table has an auto incrementing 'owner_id'.

I have a 'store_owner' row in the 'stores' table that I would like to insert the 'owner_id' into.  Is there a way to grab that value as it is being generated?

Share this post


Link to post
Share on other sites
use mysql_insert_id():
[code]
<?php
$sql = mysql_query(/* Your INSERT statement */);
$genID = mysql_insert_id();
echo "Generated ID for last query was $genID";
?>
[/code]

hope this helps

Share this post


Link to post
Share on other sites
Yep, that did it.  Here's the code I ended up with:
[code]$owner = "INSERT INTO owners (owner_name) " .
"VALUES ('$owner_name')";

$owner_results = mysql_query($owner) or die(mysql_error());
$owner_id = mysql_insert_id();

echo "Owner data inserted successfully!<br /><br />";
echo "Inserted $owner_name into the database with ID# $owner_id<br /><br />";

$store = "INSERT INTO stores (store_type, store_owner, store_state, store_zip, store_phone, store_status, store_comments) " .
"VALUES ('$store_type', '$owner_id', '$store_state', '$store_zip', '$store_phone', '$store_status', '$store_comments')";

$store_results = mysql_query($store) or die(mysql_error());
echo "Succsessfully stored $owner_name's store in the database.";[/code]

Thanks a bunch!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.