In my User
table I have phone
as unique. So when I insert duplicate phone number I want to update deviceId
, registrationId
and I want the id
which got updated. I tried this but its not working.
$stmt1 = $db->prepare("INSERT into User (name,phone, deviceId,registrationId) values(:name,:phone, :deviceId,:registrationId) ON DUPLICATE KEY UPDATE deviceId = :deviceId, registrationId = :registrationId, id=lastInsertId(id)");
Thank you..
After chatting with the OP the problem was he was not getting the ID when a record was updated. The final solution is to use id=LAST_INSERT_ID(id)
so the ON DUPLICATE KEY UPDATE
will set the id and then fetch the id with $db->lastInsertId();
$stmt = $db->prepare("INSERT into User (name,phone, deviceId,registrationId) values(:name, :phone, :deviceId,:registrationId) ON DUPLICATE KEY UPDATE deviceId = :deviceId, registrationId = :registrationId, id=LAST_INSERT_ID(id)");
Then fetch the insert id after.
$id = $db->lastInsertId();