0

I have some PDO insert code inside try catch block. I am deliberately passing wrong values to the execute function so that the insert will fail. i.e.; inserting duplicate values on a column that is declared as primary. As tested the insert query fails while executing on console, giving error:

#1062 - Duplicate entry '0' for key 'PRIMARY' 

However, my try--catch block is not catching this exception. Is it because PHP does not throw an exception for duplicate entry? I am new to PHP. Have been searching the net but cannot seem to find a clue:

try
 {  
     $query = $conn->prepare($preSQL);
     $query->execute($postSQL);  //$postSQL is the associative array for placeholders
     $dataAdded = $query->rowCount();
     $lastInsertId = $this->conn->lastInsertId();
 }
catch(PDOException $e)
 {
    fwrite($myfile,PHP_EOL);
    fwrite($myfile,$e->getMessage());
    fclose($myfile);
    return false;
 }
1

2 Answers 2

2

You might need to include the PDOException eg

use PDO;
use PDOException;
Sign up to request clarification or add additional context in comments.

Comments

1
  1. Step:

Add this code to top of the page:

error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);

use error_reporting(E_ALL) only in development mode!

  1. Step

Add the code below after your $conn = new PDO(...);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

2 Comments

then it means : its not throwing a fatal error and ur error_handling level is too low. Let me fix it for you
Done. Still the exception is escaping the catch block. Actually my php.ini was already configured to report errors. Below are the values from php.ini: </ br>error_reporting=E_ALL & ~E_DEPRECATED & ~E_STRICT </ br> display_errors=On </ br> display_startup_errors=On

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.