Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PDO query works but prepared statement does not

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading