By default the PDO issues unsuccessful query errors, since errors and exceptions are distinct things especially in php.
The simplest way to handle a crash is to get the result of execute()
$sql = $pdo->prepare("INSERT INTO usuarios (nome, email) VALUES (:nome,:email,:senha)");
$sql->bindValue(":nome",$nome);
$sql->bindValue(":email",$email);
if(!$sql->execute()){
print_r($sql->errorInfo());
}
If you really need exceptions you should flag this in the constructor by reporting the fourth argument to the array of options or via setAttribute()
. The configuration that must be modified is PDO::ATTR_ERRMODE
and its value is PDO::ERRMODE_EXCEPTION
Example in the constructor:
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO('mysql:host=localhost;dbname=catalogo', 'root', 'root', $opcoes);
Example via setAttribute()
$pdo = new PDO('mysql:host=localhost;dbname=catalogo', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
When working with exceptions always remember what problem you want to solve, or just catch the most specific exception (which will give a different treatment) in the case PDOException .
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO('mysql:host=localhost;dbname=catalogo', 'root', 'root', $opcoes);
try{
$sql = $pdo->prepare("INSERT INTO erro de sintaxe");
$sql->bindValue(":nome",$nome);
$sql->bindValue(":email",$email);
$sql->execute();
} catch(PDOException $e){
echo 'pokemon capturado com sucesso!11';
}