[BNM] PHP MySQL auto-increment value

Ali ali at nubz.com
Wed Oct 24 13:08:40 BST 2007


number 2 was close!

You must call the mysql_insert_id() AFTER you have run the query to insert the record not before as your code does - and always a good idea to include the link resource in the call also e.g. mysql_insert_id($myconnection);

hth

ali

On 24/10/2007 12:42:01, Richard Wells (richard at richard-wells.co.uk) wrote:
> I am stuck on this:
> 
> how do you recall an auto-incremented value (eg a primary key id)
> which you have just generated by inserting data into a table using a
> form, in order to insert it into the next table (as a foreign key)?
> 
> I have tried a couple of things but with erratic results:
> 
> 1. Create a session variable:
> 
> <?php
> session_start();
> if ($_POST && !empty($_POST['Contact_ID'])) {
> $_SESSION['Contact_ID'] = $_POST['Contact_ID'];
> }
> ?>
> 
> 2. Use mysql_insert_id(); to recall it, POST it in a form and then
> create a session variable:
> 
> <?php
> mysql_select_db($database_SAOS2008, $SAOS2008);
> $query_rsContact = "SELECT `Contact_ID` FROM contacts";
> $Contact_ID = mysql_insert_id();
> $rsContact = mysql_query($query_rsContact, $SAOS2008) or die
> (mysql_error());
> $row_rsContact = mysql_fetch_assoc($rsContact);
> $totalRows_rsContact = mysql_num_rows($rsContact);
> ?>
> 
> <input type="hidden" name="Contact_ID"
> value="<?php echo
> $Contact_ID; ?>" />
> 
> Richard
> --
> 
> BNM Subscribe/Unsubscribe:
> http://www.brightonnewmedia.org/options/bnmlist
> 
> List jobs for 10 pounds on Sussex Digital. Use promo code bnm10


More information about the BNMlist mailing list. Powered by Wessex Networks