By default PDO emits errors in unsuccessful query, since errors and exceptions are distinct things especially in php.
The simplest way to treat a failure is to catch 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 informing the fourth argument with the options array or via setAttribute()
. The setting 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 which problem you want to solve or capture only 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';
}
I do not understand, it does not enter the catch to inform me the error, even I forcing the error in Insert.
– Felicio Neto