来自$ _GET的值时,PDO bindValue不起作用

时间:2015-03-13 16:31:33

标签: php mysql pdo

我正在尝试使用PHP,SQL,PDO创建一个基本的评级函数,它增加了用户给予字段的评级值" recipe_rating"然后在字段中添加1" recipe_ratingcounter"。

但是,下面的代码有些不对劲!两行$ query1-> bindValue(2,$ recipename);和$ query2-> bindValue(1,$ recipename);由于它们实际上没有将任何内容绑定到SQL语句中的相应占位符,因此无法正常工作。 SQL语法是正确的,因为当上面的$ recipename变量被替换为像#34; tuna pasta"或者" spag bol"而不是$ _GET [' name']。

Var_dump在两者都显示$ recipename作为字符串:

  • $ recipename = $ _GET [' name'];

  • $ recipename =" tuna pasta";

...因此我不知道接下来要做什么,因为我已经尝试了我能想到的一切!

这有效 -

if (isset($_POST["Submit"])) {
$selectedrating = $_POST["rating"];
$recipename = "tuna pasta";

global $con;
$query1 = $con->prepare("UPDATE emptyfridge SET recipe_rating = recipe_rating + :recipe_rating WHERE recipe_name = :recipe_name1");
$query1->bindValue(':recipe_rating', $selectedrating);
$query1->bindValue(':recipe_name1', $recipename);
$query1->execute();

$query2 = $con->prepare("UPDATE emptyfridge SET recipe_ratingcounter = recipe_ratingcounter + 1 WHERE recipe_name = :recipe_name2");
$query2->bindValue(':recipe_name2', $recipename);
$query2->execute();
}

但这不起作用 -

if (isset($_POST["Submit"])) {
$selectedrating = $_POST["rating"];
$recipename = $_GET['name'];

global $con;
$query1 = $con->prepare("UPDATE emptyfridge SET recipe_rating = recipe_rating + :recipe_rating WHERE recipe_name = :recipe_name1");
$query1->bindValue(':recipe_rating', $selectedrating);
$query1->bindValue(':recipe_name1', $recipename);
$query1->execute();

$query2 = $con->prepare("UPDATE emptyfridge SET recipe_ratingcounter = recipe_ratingcounter + 1 WHERE recipe_name = :recipe_name2");
$query2->bindValue(':recipe_name2', $recipename);
$query2->execute();
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:-1)

bindValue用于原始值。例如:

$sql->bindValue(":val1", "tuna pasta");
$sql->bindValue(":val2", 1234);

您必须对变量中的值使用bindParam。例如:

$var1 = "tuna pasta";
$var2 = 1234;
$sql->bindParam(":val1", $var1);
$sql->bindParam(":val2", $var2);