0
votes

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;
 }
2

2 Answers

1
votes
  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);
1
votes

You might need to include the PDOException eg

use PDO;
use PDOException;