0

I have the written the following code which works fine and shows me the nickname:

$stmt2 = $pdo->query("SELECT nick FROM users WHERE ID=12");
$nn = $stmt2->fetch();
echo $nn["0"];

now I tried to do it as a prepared statement, so I can use different ID numbers. But it does not work, it display nothing.

$stmt3 = $pdo->prepare("SELECT nick FROM users WHERE ID=?");
$stmt3->execute(12);
$nn3 = $stmt3->fetch;
echo $nn3["0"];

I tried looking if I did something wrong but i simply can not see what is wrong the prepared statement.

Bodongo
  • 11
  • 1

1 Answers1

0

You need to pass an array as the argument to the execute method when using a prepared statement. The argument should contain the values that you want to bind to the placeholders in the prepared statement. In your case, you need to pass an array containing the value of the ID you want to use as the parameter in the query.

$stmt3->execute([12]);

You are missing the () after fetch when trying to retrieve the result from the prepared statement. The fetch method returns a row from the result set as an array, so you need to call it like a function to retrieve the result.

$nn3 = $stmt3->fetch();

When accessing an element in the array returned by fetch, you need to use the key of the element, not its index. In this case, you can use the key "nick" to access the nickname.

echo $nn3["nick"];

Here's the corrected code:

$stmt3 = $pdo->prepare("SELECT nick FROM users WHERE ID=?");
$stmt3->execute([12]);
$nn3 = $stmt3->fetch();
echo $nn3["nick"];