NotionCommotion Posted March 23, 2017 Share Posted March 23, 2017 Consider the following. Is it possible to do so database vendor agnostic? <?php function testException($pdo,$sql,$data) { try { $stmt=$pdo->prepare($sql); $stmt->execute($data); echo("NO ERROR FOR $sql\n"); } catch (PDOException $e) { $error = $stmt->errorInfo(); echo("SQL: $sql\n"); if($error[0]==23000 && $error[1]==1062) { echo("Do something for: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry\n\n"); } elseif($error[0]==23000 && $error[1]==1451) { echo("Do something for: SQLSTATESQLSTATE[23000]: Integrity constraint violation: 1451 foreign key constraint fails\n\n"); } else { throw $e; } } } $db=parse_ini_file('../../config.ini',true)['mysql']; $pdo = new \PDO("mysql:host={$db['host']};dbname={$db['dbname']};charset={$db['charset']}",$db['username'],$db['password'],array(\PDO::ATTR_EMULATE_PREPARES=>false,\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION,\PDO::ATTR_DEFAULT_FETCH_MODE=>\PDO::FETCH_OBJ)); $sql='INSERT INTO sources_type(type,name) VALUES(?,?)'; $data=['client','my name']; testException($pdo,$sql,$data); $sql='DELETE FROM sources_type WHERE type=?'; $data=['client']; testException($pdo,$sql,$data); Quote Link to comment https://forums.phpfreaks.com/topic/303521-responding-to-specific-sql-errors/ Share on other sites More sharing options...
requinix Posted March 23, 2017 Share Posted March 23, 2017 The first number is a standardized error code that will probably only give you a general explanation as to what the problem was. Compare MySQL's error codes with PostgreSQL's and you'll see MySQL uses SQLSTATE 23000 for no less than fourteen distinct error conditions while PostgreSQL uses just the one. The second number is vendor-specific. So no. Quote Link to comment https://forums.phpfreaks.com/topic/303521-responding-to-specific-sql-errors/#findComment-1544492 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.