Mysql If question
I am making a chatbox IM.
I have a table where I want to update if the user closes the window, meaning he has viewed the messages his friend has sent him. When this happens, each conversation has a unique id so I find messages with that id and set the viewed column equal to the users name.However if the other user also closes the window I would like to change the viewed column to 'both' for all the messages so none of those messages pops up for either user. (by default the viewed column is equal to 0).
What I want is a query that just finds all the messages with theconvo_id
and if that message is already viewed by another user meaning viewed!=0
then it is set to both else it is set to the user closing the box.
I have a query but it doesn't work because I didn't quite get the syntax right.
Just wondering if anyone could correct it or suggest something.
$sql = "UPDATE chatbox IF (viewed!=?) THEN
SET viewed=? WHERE convo_id=?
ELSE
SET viewed=? WHERE convo_id=?";
$stmt18 = $conn->prepare($sql);
$result = $stmt18->execute(array(0,$receiver,$convo_id,'both',$convo_开发者_如何学Pythonid));
you'll want to use a case statement:
update catbox
set viewed = case when viewed = ? THEN ? else ? end
where convo_id = ?
I propose that you create a second table (perhaps called 'views') to record this information. When the close event occurs, you insert a line into the table with the message id and the username.
This should simplify the query and avoid the creation of confusing data in the message table.
精彩评论