I have simple insert/update page where I do check if there is “id”, if no then proceed insert query otherwise proceed update query, and this works fine. Problem is that I need that id for the next query, in case of Insert query I will get it as “lastInsertId” but in case of Update query “lastInsertId” will overwrite $_POST[“id”].
Is there a way to identify which query has been performed (insert or update) and then get right id, or I have to bind/ execute query’s separately?
$id= $_POST["id"];
try {
$DBH = db_connect ();
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($id== "") {
$query= $DBH->prepare('INSERT INTO table (x1,x2) VALUES(:x1,:x2)');
} else {
$query= $DBH->prepare('UPDATE day SET x1=:x1, x2=:x2 WHERE id= :id');
$query-> bindValue(':id', $id);
}
$query-> bindValue(':x1', $x1);
$query-> bindValue(':x2', $x2);
$query-> execute();
$id= $DBH-> lastInsertId('id') ; //get last inserted ID
}
You can use exactly the same if clause as for picking the insert query as the query to excecute. Then your code would look like this: