3
votes

I want to update my MYSQL table, but with a condition.

I have a status field and a time field. If status=day, don't update time field with the current time. if status=night, update time field with current time.

Right now, I am doing a SELECT statement, then an if statement on the returned value in PHP and then performing the UPDATE and changing all fields except the time unless status=night. Is it possible to do this all in one command?


Edit:

Sorry, just to clarify:

A WHERE command will only update the row if status=night. I always want all the fields within the row to be updated, but only update the time field if status=night. If status=day, update the entire row except for the time field.


Code:

if($status=="night") {
    $query = "UPDATE post SET name="$name", comment="$comment", status="$status", time="{now()}" WHERE id='$id'";
} else {
    $query = "UPDATE post SET name="$name", comment="$comment", status="$status" WHERE id='$id'"
}
2
show us you actual code then we can make suggestions. - user557846
A WHERE clause would be like UPDATE table SET time=time() WHERE status='status'. I want it to update the row no matter what the status is, but only change the time field if status=night. - steeped
It would be easy to assist, if you provide those two MySQL query you are using. - Mayura
Quickly typed out the code and through it into original post - steeped

2 Answers

5
votes
UPDATE table
SET field1 = val1, time=IF(status="night",NOW(),time), field3= val3;
0
votes

This should do it:

UPDATE `table` SET `time` = NOW() WHERE `status` = `night`