The forums have permanently moved to forum.kirupa.com. This forum will be kept around in read-only mode for archival purposes. To learn how to continue using your existing account on the new forums, check out this thread.


Results 1 to 6 of 6

Thread: mysql_insert_id() doesn't work

  1. #1

    mysql_insert_id() doesn't work

    Hi,

    I've attempted about 20 different variations of what is effectively the same job; and I just can't get it to work.

    I've inserted some information into the mysql database. Now all I want is to return the ID. The ID is auto_increment and has Zerofill. I'm not sure if this is effecting my attempt, but all I get is a single 0. What am I doing wrong?

    Code:
    $SQL = "INSERT INTO db_table (name, email) VALUES ('$name', '$email')";
    echo "The last inserted ID was : " . mysql_insert_id();
    Thanks, Mark.

  2. #2
    You also need to make sure that the ID column is marked as the "primary key".

  3. #3
    Yes, it was also set as the primary key. Still doesn't work.

  4. #4
    Even when I simplify it still just returns the number 0;

    Code:
    $lastItemID = mysql_insert_id();
    echo "$lastItemID";
    I can only assume I've not set up the ID field correctly. This is how the ID field is set up:

    Field: ID
    Type: smallint(6)
    Collation: BLANK
    Attributes: BLANK
    Null: No
    Defualt: BLANK
    Extra: auto_increment
    Primary: Yes
    Unique: No
    Index: No

  5. #5
    Argh! I figured out what I was doing wrong, and I deserve a right slap around the face as discipline for my stupidity.

    I was calling the mysql_query AFTER I was trying to get the ID. I was effectively asking for the ID before I even inserted anything to the database.

    Code:
    $SQL = "INSERT INTO db_table (name, email) VALUES ('$name', '$email')";
    
    $result = mysql_query($SQL);
    
    echo "The last inserted ID was : " . mysql_insert_id();

  6. #6
    jwilliam's Avatar
    476
    posts
    An intellectual carrot!
    Also... if you're interested at all, there is a safer way to retrieve the last insert id than PHP's built-in function. Try this:

    PHP Code:
    function lastInsertId()
    {
      
    $sql "SELECT LAST_INSERT_ID() AS id;";
      
    $result mysql_query($sql);
      
    $row mysql_fetch_assoc($result);
      return(
    $row['id']);

    I know for sure that mysql_insert_id() doesn't work on BIGINTs, whereas this function does. I think there may be some other instances where this is better... but I can't recall.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012