I have a table with a column that must have UNIQUE values (but it could be also a multiple-column UNIQUE index, the problem is the same). In my PHP script I have to insert a row in that table.
I'm searching for a way, not MySQL-specific, to exit the PHP script if there's a problem, and the problem is not a violation of a UNIQUE constraint. To make things more easy I don't want to use a SELECT query before :D
Currently I'm doing something like this:
try
{
$stmt = $dbh->prepare($someinsertquery);
$stmt->bindParam(':somecol', $somecol);
$stmt->execute();
}
catch (PDOException $e)
{
$errcode = $e->getCode();
if (! ($e->getCode() === '23000'))
{
echo 'Error inserting into db: ' . $e->getMessage();
var_dump($e->getTrace());
exit();
}
}
The problem is that this way I miss also errors related to foreign keys. I think it's okay if I can't have foreign keys problems inserting a new row, but what if I'll change the table in future? I could use
PDOStatement::errorInfo[1]
but it is a driver specific error code. The same with ON DUPLICATE KEY UPDATE.