我正在尝试使用 PHP、SQL、PDO 创建一个基本评级函数,它将用户给出的评级值添加到“recipe_ rating”字段,然后将 1 添加到“recipe_ ratingcounter”字段。
但是,我的下面的代码有些不太正确!两行 $query1->bindValue(2, $recipename);
和 $query2->bindValue(1, $recipename);
无法正常工作,因为它们是实际上并没有将任何内容绑定(bind)到 SQL 语句中相应的问号。我相信 SQL 是正确的,因为当我将上面几行中的这些 $recipename
变量替换为“Tuna Pasta”等字符串时,整个函数完美运行。我还在这个变量上使用了 var_dump 以确保它确实包含一个字符串。
if (isset($_GET['name'])) {
$name = $_GET['name'];
$recipedetails = $recipe->get_recipe($name);
if (isset($_POST["Submit"])) {
$selectedrating = $_POST["rating"];
$recipename = $recipedetails['recipe_name'];
$recipename = "'".$recipename."'";
global $con;
$query1 = $con->prepare("UPDATE emptyfridge SET recipe_rating = recipe_rating + ? WHERE recipe_name = ?");
$query1->bindValue(1, $selectedrating);
**$query1->bindValue(2, $recipename);**
$query1->execute();
$query2 = $con->prepare("UPDATE emptyfridge SET recipe_ratingcounter = recipe_ratingcounter + 1 WHERE recipe_name = ?");
**$query2->bindValue(1, $recipename);**
$query2->execute();
}
最佳答案
使用bindValue替换前面带有冒号的占位符变量:
http://php.net/manual/en/pdostatement.bindvalue.php
具体:
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
就您而言:
$query1 = $con->prepare("UPDATE emptyfridge SET recipe_rating = recipe_rating + :recipe_rating WHERE recipe_name = :recipe_name");
$query1->bindValue( ':recipe_rating', $selectedrating );
$query1->bindValue( ':recipe_name', $recipename );
关于PHP PDO BindValue 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024613/