问题
I got a query like :
"UPDATE snakes_tb
SET snake_pic_urls= CONCAT(snake_pic_urls,'*".$newSnakePic."'),
snake_default_pic = '".$Set_a_Value_here_only_if_this_field_is_empty_or_equal_to_NO_PIC."' WHERE snake_id={$id}"
What can possibly be done to satisfy the snake_default_pic
field's condition before setting it's value? Thanks.
回答1:
Try this:
UPDATE snakes_tb
SET snake_pic_urls= CONCAT(snake_pic_urls,'*".$newSnakePic."'),
snake_default_pic = IF(snake_default_pic = '' OR snake_default_pic = 'NO_PIC' ,'default_pic',snake_default_pic)
WHERE snake_id={$id}
If snake_default_pic
is empty or equal to NO_PIC then it will be updated to default_pic
otherwise it will keep the same value
回答2:
Just update the where to only update where there's no pic:
UPDATE snakes_tb
SET snake_pic_urls= CONCAT(snake_pic_url,'*".$newSnakePic."'),
snake_default_pic = '".$pic."'
WHERE snake_id={$id}
AND (snake_default_pic = '' OR snake_default_pic='NO_PIC')
Be aware that you're code is also vulnerable to SQL injection. Prepared statements can help prevent this.
来源:https://stackoverflow.com/questions/17407987/mysql-update-is-it-possible-to-confirm-some-fields-first