Jump to content


Photo

Can I retreive an auto increment value on the fly?


  • Please log in to reply
2 replies to this topic

#1 pseudomega

pseudomega
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 01 September 2006 - 06:48 PM

This is my current INSERT statement which uses POST'ed data from an HTML form:
$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')";

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?

#2 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 01 September 2006 - 07:20 PM

use mysql_insert_id():
<?php
$sql = mysql_query(/* Your INSERT statement */);
$genID = mysql_insert_id();
echo "Generated ID for last query was $genID";
?>

hope this helps
You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#3 pseudomega

pseudomega
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 01 September 2006 - 07:37 PM

Yep, that did it.  Here's the code I ended up with:
$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.";

Thanks a bunch!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users