I have a problem with PDO::lastInsertId()
method which doesn't return the id (primary key) of last inserted row, instead it returns another field which is a foreign key field.
PHP code:
$pdo = new PDO(...);
$stmt = $pdo->prepare($sql);
$stmt->bindParam(...);
$stmt->bindParam(...);
$stmt->execute();
$id = $pdo->lastInsertId();
// or
$id = $pdo->lastInsertId('services_id_seq'); // I think 'services_id_seq' is not necessary in MySQL
// both of them don't return the primary key of last inserted row
echo 'last inserted id: ' . $id;
MySQL Table structure:
...
id int unsigned not null primary key auto_increment
customer_id int unsigned not null
user_id int unsigned not null
....
inserted row in MySQL:
id customer_id user_id ...
1 19 31 ...
PHP output:
last inserted id: 19
It should return 1
not 19
. I don't know is anything wrong with my code or not.. or maybe this is the normal behavior :?
Return Value (PHP documentation):
If a sequence name was not specified for the name parameter,
PDO::lastInsertId()
returns a string representing the rowID
of the last row that was inserted into the database.If a sequence name was specified for the name parameter,
PDO::lastInsertId()
returns a string representing the last value retrieved from the specified sequence object.If the
PDO
driver does not support this capability,PDO::lastInsertId()
triggers anIM001 SQLSTATE
.