How to use Try Catch on an Insert

Asked

Viewed 2,538 times

3

How do I use a Try catch to return an error from an Insert that was not inserted into the database. For example

$sql = $pdo->prepare("INSERT INTO usuarios (nome,email,senha,telefone) VALUES (:nome,:email,:senha,:telefone)");
   $sql->bindValue(":nome",$nome);
   $sql->bindValue(":email",$email);
   $sql->bindValue(":senha",md5($senha));
   $sql->bindValue(":telefone",$telefone);
   $sql->execute();

How can I check to know if it was really inserted and if not, return me the error.

5 answers

3

Instead of using Exception use Pdoexceptioninserir a descrição da imagem aqui

  • I do not understand, it does not enter the catch to inform me the error, even I forcing the error in Insert.

1

In case you would have to work with the exception class of php the class (Exception), I put a basic example here following the line of your code, but there is a more correct way to work with it.

http://php.net/manual/en/language.exceptions.php

try
{

   $sql = $pdo->prepare("INSERT INTO usuarios (nome,email,senha,telefone) VALUES (:nome,:email,:senha,:telefone)");
   $sql->bindValue(":nome",$nome);
   $sql->bindValue(":email",$email);
   $sql->bindValue(":senha",md5($senha));
   $sql->bindValue(":telefone",$telefone);
   $sql->execute();

}
catch(Exception $e)
{
    echo $e->getMessage();
}
  • He doesn’t get in the catch, even though I forced the mistake. I don’t know why.

  • 1

    What version of php are you using? And in your php.ini have you checked whether the php error option is enabled to be shown on the screen? Maybe this is more related to how your development environment or production environment is set up.

1

Good afternoon!

The PDO execute() method returns a boolean that indicates whether there has been success or failure in SQL execution (http://php.net/manual/en/pdostatement.execute.php).

In your case, you can do so:

public function insereDados($nome, $email, $senha, $telefone) {
    if (!$nome || !$email || !$senha || !$telefone) {
        throw new DadosNaoPreenchidosException("Dados incompletos!");
    }

    $sql = $pdo->prepare("INSERT INTO usuarios (nome,email,senha,telefone) VALUES (:nome,:email,:senha,:telefone)");
    $sql->bindValue(":nome",$nome);
    $sql->bindValue(":email",$email);
    $sql->bindValue(":senha",md5($senha));
    $sql->bindValue(":telefone",$telefone);
    $sucesso = $sql->execute();
    if (!$sucesso) {
        throw new SqlException("Mensagem de erro");
    }
}

You can create exceptions to treat them individually outside the method that calls it, thus: https://secure.php.net/manual/en/language.exceptions.extending.php

class SqlException extends SystemException {
    public __construct($mensagem) {
        parent::__construct($mensagem, 0);
    }
}

And then, you treat your exceptions in the call of methods:

//faz alguma coisa
try {
    $obj->insereDados("João da Silva", "[email protected]", "123", "(11) 1111-1111");
} catch (DadosIncompletosException $e) {
    echo "Dados não preenchidos";
} catch (SqlException $e) {
    echo "Erro ao executar o SQL";
}
  • The idea is good and works, but I tried to use directly with Tray catch, and in no way even forcing error, it does not catch to present me the error.

  • you can add a snippet of your code for analysis?

  • 1

    His code worked, but he wanted to use Try catch straight, without treating the error, but using methods handled by people he does not enter the catch.

  • And if you used one of the ways of error handling PDO? $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

1

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

0

Browser other questions tagged

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