Is there a way to get the record identifier (primary key) after insertion when the mysql error returns a duplicate key?
eg. How would I do this:
$sql = "INSERT INTO table (`col1`, `col2`) VALUES ('$val1', '$val2')"; $result = mysql_query($sql); if($result){ $id = mysql_insert_id(); } else { if(stristr(mysql_error(), "duplicate"){ $sql = "SELECT `id` FROM `table` WHERE `col1`='$val1' AND `col2`='$val2'"; $result = mysql_query($sql); $row = mysql_fetch_array($result); $id = $row['id']; } else { die(mysql_error()); } }
Here I needed to make two sql-operators, which not only require time and effort, but also duplicate the code.
I cannot use ON DUPLICATE KEY UPDATE
because I want to update another table using either the last inserted identifier or the identifier of a record that cannot be duplicated.
So, am I right in what I do? Or is there a way to get the row id?
thanks
source share