![](/img/trans.png)
[英]Only Update a certain column in MySQL Query if it has a certain value set
[英]update certain table column if else query
我正在嘗試編寫查詢以檢查要更新的列。 用戶發送他們執行的操作(喜歡或評論),而我正在嘗試更新表。 是否可以在查詢中檢查要更新的列? 例如:
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'");
如果有可能,我不確定該如何表達。 有什么建議嗎? 提前致謝!
盡管meverhart913可以做到這一點,但做同一件事的更好方法是根據if條件實例化變量,然后將變量插入字符串中。 這使您不必一遍又一遍地重復字符串,還可以輕松添加其他條件。
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
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'");
}
我不是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";
然后執行它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.