简体   繁体   中英

How to return 1 in mysql_insert_id() in php?

The logical error here is that the mysql_insert_id() always starts at 0 and I want it to increment from 1 and so on. I wonder why it gives me an error: Duplicate entry '0' for key 'PRIMARY'. I don't want to duplicate the key I just want to add it. eg. 1 2 3 4.

Here's my code:

$insertID=mysql_insert_id(); //I want this to start at 1

        if (isset($_POST['lastname']) && isset($_POST['firstname']) && isset($_POST['address']))
        {
            $sql="INSERT INTO contact(idnum, lastname, firstname, address) values ('$insertID','$_POST[lastname]','$_POST[firstname]','$_POST[address]')";

            if(!mysql_query($sql, $con))
            {
                    die("Error: " .mysql_error());
            }
            echo "Saved...";
        } 

You seem to be misunderstanding what mysql_insert_id() actually does .

It doesn't generate an ID for you to use in your next query. It tells you the ID that MySQL generated in the last query. So...

  1. If your table isn't using an auto-generated ID, there's no generated ID for the database to return.
  2. You're asking for the generated ID before you insert anything.

If you're using a manual ID, then it's the responsibility of your application to generate a unique one. If you're using a database-generated ID, then remove the ID from your INSERT statement and get the ID from the database after it's been generated.


Also, side note, your code is wide open to SQL injection vulnerabilities .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM