简体   繁体   中英

Get last inserted ID in prepared statement

I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.

Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style? I have tried to apply it to my code but I am still not getting the right response.

   if($data->edit_flag == 'ADDED')
        {

            $rowdata[0] =   $data->location_name;  
            $rowdata[1] =   0;  
            $rowdata[2] =   $data->store_id;

            $query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";

            $statement = $conn->prepare($query);
            $statement->execute($rowdata);
            $id = mysqli_stmt_insert_id($statement);
            echo "inserted id: " . $id;
        }       

I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following

$id = $conn->lastInsertId();
echo "insert id: " . $id;

but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:

$statement = $conn->prepare($query);
$statement->execute($rowdata);

You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation

        $statement = $conn->prepare($query);
        $statement->execute($rowdata);
        $id = $conn->lastInsertId();

Some potential reasons why it is not working:

  1. Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
  2. Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.

Hope this helps!

If you are using pdo,

$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();

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