如何更改此SQL以执行以下操作:
favourite_active = 0
将其更改为favourite_active = 1
。favourite_active = 1
将其更改为favourite_active = 0
。我需要添加WHERE子句。
$result = mysql_query("SELECT * FROM tbl_favourites WHERE (user_id = '$who' AND favourite_id = '$usernum' AND favourite_active = '1')");
// if user does not exist in favourites, add them
if(mysql_num_rows($result) == 0)
{
mysql_query("INSERT INTO tbl_favourites (user_id, favourite_id, favourite_active) VALUES ('$who', '$usernum', '1')");
echo"You have added this user as a favourite";
}
// if user does exist and favourite_active = 1 change to 0
else {
mysql_query("UPDATE tbl_favourites SET favourite_active='0' WHERE user_id='$who' AND favourite_id='$usernum'");
echo"You have removed this user as a favourite";
}
// if user does NOT exist and favourite_active = 0 change to 1
else {
mysql_query("UPDATE tbl_favourites SET favourite_active='1' WHERE user_id='$who' AND favourite_id='$usernum'");
echo"You have removed this user as a favourite";
}
答案 0 :(得分:1)
您在IF中不能有两个else
子句。并且您无法在两个单独的查询中执行UPDATE
,因为第二个查询只会撤消第一个查询。使用以下查询:
UPDATE tbl_favourites SET favourite_active = NOT favourite_active WHERE user_id = '$who' and `favourite_id = '$usernum'
我也不确定你说的第一部分是否有效。您的SELECT
查询专门针对favourite_active = 1
。如果用户已与favourite_active = 0
存在,您将尝试INSERT
他们。这真的是你想要的吗?也许你应该删除AND favourite_active = '1'
。
如果user_id
和favourite_id
在表格上形成唯一索引,您可以在一个查询中执行整个操作:
INSERT INTO tbl_favourites (user_id, favourite_id, favourite_active)
VALUES ('$who', '$usernum', '1')
ON DUPLICATE KEY UPDATE favourite_active = NOT favourite_active