PHP - detect mysql update/insertion failure due to violated unique constraint

前端 未结 7 1254
无人及你
无人及你 2020-11-30 11:10

This is kind of similar to this question:

PHP MySQL INSERT fails due to unique constraint

but I have a different twist. Let\'s say I have a table with only

7条回答
  •  有刺的猬
    2020-11-30 11:50

    Now that it's the year 2015, there are very few reasons not to be using PHP's PDO implementation:

    http://php.net/manual/en/book.pdo.php

    The proper, modern, "OO" method for detecting and handling an insertion failure due to a key constraint violation is as follows:

    try {
        //PDO query execution goes here.
    }
    catch (\PDOException $e) {
        if ($e->errorInfo[1] == 1062) {
            //The INSERT query failed due to a key constraint violation.
        }
    }
    

    The PDOException object has a lot more to say about the specific nature of the error, too (more detail than one could possibly ever want or need, seemingly).

    http://php.net/PDOException

提交回复
热议问题