Error adding elements in MySQL database with PDO

2

I'm having the following error while inserting into the database:

  

Parse error: syntax error, unexpected '{', expecting '(' in /var/www/public/Test/db/add-banco.php on line 18

Line 18 is: } catch {

<?php 
$host = "localhost"; 
$dbname = "scotchbox";
$user = "root";
$pass = "root";

try {
    // Abre a conexão com o DB
    $conn = new PDO("mysql:host = $host; dbname = $dbname", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Faz a operação de INSERT no DB
    $stmt = $conn->prepare("INSERT INTO usuarios (nome, idade) VALUES (:nome, :idade)");
    $stmt = bindParam(":nome", $_POST["nome"]);
    $stmt = bindParam(":idade", $_POST["idade"]);
    $stmt->execute();

    echo "Valores inseridos com sucesso!";
} catch {
    echo "ERRO: " . $e->getMessage(); 
}
?>
    
asked by anonymous 31.05.2016 / 15:21

2 answers

2

It has a small syntax:

should look like this:

$stmt = $conn->prepare("INSERT INTO usuarios (nome, idade) VALUES (:nome, :idade)");
$stmt->bindParam(":nome", $_POST["nome"]);
$stmt->bindParam(":idade", $_POST["idade"]);
$stmt->execute();

And in the line of catch put:

...catch (Exception $e) {
    echo "ERRO: " . $e->getMessage();
}

In this case, we print out any exceptions that happen

    
31.05.2016 / 15:32
0

In the missing code you specify which exception to capture, in this case the PDOException. Prefer to capture the most specific exception to know where the code failed and have the necessary details, leaving the most generic Exception , any one posted diverts the stream to catch which in this case works as a drain or anything can flow into it.

change:

} catch {

To:

} catch(PDOException $e) {

Recommended reading:

What exception should I post according to each situation?

What's the difference between PHP Exception?

    
31.05.2016 / 15:41