PHP / MySQL语句。 如何将其转换为准备好的声明? [关闭]

PHP / MySQL语句。 如何将其转换为准备好的声明?  [关闭]

问题描述:

$query = 'INSERT INTO user_answer (facebook_id, answer_id) VALUES (' . $i . ',' . $randAnswer . ')';
$dbh->exec($query);

I have this code, and now am required to turn it into a prepared statement using PDO::bindValue() and maybe PDO::prepare(). Looking at the examples, I'm not sure how to go about this. Where does the :name come from and why are you putting it in the bindValue part?

In your case it would look something like this:

$st = $dbh->prepare("INSERT INTO user_answer (facebook_id, answer_id) VALUES (:facebook_id, :answer_id)");

$st->execute(array('facebook_id' => $i, 'answer_id' => $randAnswer));

You might want to read a tutorial or two to get an idea how to use PDO effectively. The PDO documentation is also pretty good.

The general idea here is to put in things like :name where the name value goes, and then pass in an array that defines what name maps to.

it looks way better without useless labels

$query = 'INSERT INTO user_answer (facebook_id, answer_id) VALUES (?,?)';
$stmt  = $dbh->prepare($query);
$stmt->execute(array($i,$randAnswer));

At least your query fits into screen.