Error adding elements in Mysql Database with PDO

Asked

Viewed 63 times

2

I am having the following error while inserting into the database:

Parse error: syntax error, Unexpected '{', expecting '(' in /var/www/public/Test/db/add-bank.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(); 
}
?>
  • Where is line 18?

  • I have an error in this code here $stmt = bindParam(":nome", $_POST["nome"]); and $stmt = bindParam(":idade", $_POST["idade"]); would have to be so: $stmt->bindParam(":nome", $_POST["nome"]); and $stmt->bindParam(":idade", $_POST["idade"]);, that is, is not equal is access to class method, attention.

  • Row 18: } catch {

2 answers

2

Has a little syntax:

it must be so:

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

And on the line of catch put:

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

In this case we print any exception that happens

  • 1

    IT WORKED!!! VLW!

  • You’re welcome @Giovannicruz

0

The code lacked specifying which Exception to capture, in the case of Pdoexception. Prefer to capture the more specific exception to know where the code failed and have the necessary details, while leaving the more generic Exception, any launch will divert the flow to the catch which in this case works like a drain or whatever can drain into it.

change:

} catch {

To:

} catch(PDOException $e) {

Recommended reading:

Which Exception should I release according to each situation?

What is the difference between the PHP "Exception"?

Browser other questions tagged

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