How to use Try Catch in an insert

2

How do I use a try catch to return me 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 see if it was actually inserted and if not, to return the error.

    
asked by anonymous 28.06.2018 / 22:14

4 answers

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, however there is a more correct way to work with it.

link

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();
}
    
28.06.2018 / 22:24
1

Good afternoon!

The execute () method of the PDO returns a boolean indicating whether SQL execution has succeeded or failed ( link ).

In your case, you can do this:

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 calling method, like this: link

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

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

//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";
}
    
28.06.2018 / 22:30
1

Instead of using Exception use PDOException

    
29.06.2018 / 03:07
1

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';
}
    
29.06.2018 / 17:02