Tracking error in PDO update request

I have an update request

$ query = $ db-> prepare ("UPDATE user SET UserID = '6', UserName = 'xyz' WHERE UserID = '6'"); $ Query-> Execute ();

it works fine, but when I change the Username field to UserNamee

$ query = $ db-> prepare ("UPDATE user SET UserID = '6', UserNamee = 'xyz' WHERE UserID = '6'"); $ Query-> Execute ();

It should show an error, but does not detect an error

I just want to handle such errors in my project.

+4
source share
4 answers

you can track the error in PDO using the errorCode () function, this function returns 0000 when no error has returned a 4-digit number (error code), as an example you can try:

 $query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' "); $query->execute(); if($query->errorCode()=='0000') { echo 'no error'; } else { echo 'error'; } 
+1
source

PDO has various error modes that can be passed to the constructor as an argument to driver_options . You can find them at http://php.net/manual/en/pdo.setattribute.php . Most people use array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) .

0
source

You should use try-catch:

  try { $query = $db->prepare("UPDATE user SET UserID='6',UserName='xyz' WHERE UserID= '6' "); $query->execute(); } catch (PDOException $e) { echo $e->getMessage(); } 

And do not forget to do this after connecting to the database:

 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
0
source
  $db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); $query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' "); if (!$query) { print_r($db->errorInfo()); } else $query->execute(); 
-1
source

Source: https://habr.com/ru/post/1479870/


All Articles