简体   繁体   中英

Primary key violation does not raise error in PHP

I am using PHP with sqlsrv_query and have an issue where an SQL error is not... causing an error.

For example, this code where user_id 1 already exists

$sqlresult = sqlsrv_query($db_conn, "INSERT into dbo.users( user_id, name)
                VALUES( 1, 'Adam');");
if( $sqlResult === false ) {
    echo "\nSQL result indicated a failure\n";
    die(  print_r( sqlsrv_errors(), true));
}   

$sqlresult is not false, despite the sql query failing with a primary key violation.

SQL Studio shows the following

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint 'PK_users'. Cannot insert duplicate key in object 'dbo.users'. The duplicate key value is (1).
The statement has been terminated.

If i try the INSERT with a bad data type, ie 'xyz' for the user_id, I do not see "The statement has been terminated.". And if executed from PHP, $sqlresult is correctly false.

The primary key violation needs to be fixed, but I am concerned that certain 'types' of errors are being silently ignored.

Any ideas why one type of error is treated differently over another?

The user_id column may be a primary key in dbo.users tables. Hence its not accepting duplicate values.

There are multiple ways of handling this issue.

  1. Make sure the user_id is not present in the table. something like MAX(user_id) + 1 .
  2. Make user_id column as AUTOINCREMENT, so that you dont have to worry about the next ID and change you insert query like this INSERT into dbo.users(name) VALUES('Adam')

I would prefer to implement in the 2nd way(with the AUTOINCREMENT), which is more cleaner approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM