PDO does not return error even in a Try catch block

Asked

Viewed 49 times

1

I was trying to register in a mysql database using PDO. Do not register but even so I did not have an error return despite the block try catch. I later discovered that the error was the column size telefone, in the bank was 11, but was passing a string with size 13. How to make the impression of the error in this case since the try catch doesn’t do that?

<?php
function save($dados){
    try{
        $pdo = new PDO("mysql:host=127.0.0.1; dbname=projetocadastro;", "root", "123456");
        $sql = 'INSERT INTO tb_clientes(nome, cpf, telefone, email, nascimento, estado, cidade, bairro, rua, numero) VALUES (:nome, :cpf, :telefone, :email, :nascimento, :estado, :cidade, :bairro, :rua, :numero);';
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':nome', $dados['nome']);
        $stmt->bindValue(':cpf', $dados['cpf']);
        $stmt->bindValue(':telefone', $dados['telefone']);
        $stmt->bindValue(':email', $dados['email']);
        $stmt->bindValue(':nascimento', $dados['dtnasc']);
        $stmt->bindValue(':estado', $dados['estado']);
        $stmt->bindValue(':cidade', $dados['cidade']);
        $stmt->bindValue(':bairro', $dados['bairro']);
        $stmt->bindValue(':rua', $dados['rua']);
        $stmt->bindValue(':numero', $dados['numero']);
        $stmt->execute();
    }
    catch (PDOException $e){
        echo $e->getMessage();
    }finally{
        $pdo = null;
    }
}
save($_POST);
?>

1 answer

5


Change the error mode from its PDO class to PDO::ERRMODE_EXCEPTION:

$pdo = new PDO(
    "mysql:host=127.0.0.1; dbname=projetocadastro;", 
    "root",
    "123456",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
  • 1

    You can remove these loose quotes in the last line?

  • Yeah, it was a typo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.