I can’t figure out why the id returned with mysqli_insert_id() is different than my expected id. Here is my code:
$query = "INSERT INTO payments_table (payment_type, payment_number, payment_cost, insertion_date) VALUES ( '$paymentType', '$paymentNumber', '$totalCost', NOW())";
$data = mysqli_query($dbc, $query);
$currentPayerID = mysqli_insert_id($dbc);
//DEBUG
echo 'current payerID is: ' . $currentPayerID;
Since there are currently 2 rows, I expect it to echo “current payerID is 3” after the next execution. However, after executing this code, it echoes the following:
“current payerID is 21”
A couple notes:
- This ‘payments_table’ table has a column named “payer_id” that is a
primary key and has the AUTO_INCREMENT attribute. - I’ve “truncated” this table(I believe this is the same as emptying it out).
I searched throughout stackoverflow, but some of the answer don’t believe that what I’m finding is possible. I appreciate any generous help!
mysqli_insert_idreturns the lastAUTO_INCREMENTvalue – if you’re inserting to another table afterpayments_tablebut before callingmysqli_insert_idyou may be getting an unexpected value.Also an
AUTO_INCREMENTcolumn does not correspond with the number of rows in the database table, but the total number of rows over the lifetime of the table. More precisely, MySQL maintains a counter variable that is incremented each time a new row is created.The following query will show the next expected
AUTO_INCREMENTvalue for a table: