我正在尝试编写查询来检查要更新的列。用户发送他们执行的操作(类似或评论),我正在尝试更新表。是否可以在查询内部检查要更新的列?例如:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
如果有可能的话,我不知道怎么说出来。有什么建议?提前谢谢!
答案 0 :(得分:2)
虽然meverhart913有办法做到这一点,但做同样事情的更好方法是根据if条件实例化变量,然后将该变量插入到字符串中。这使您不必一遍又一遍地重复您的字符串,并允许您轻松添加其他条件。
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
答案 1 :(得分:1)
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
答案 2 :(得分:0)
我不是php程序员,所以我的语法不正确,但这有两种方法:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
或者
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
然后执行它。