MYSQL UPDATE: Is it possible to confirm some fields first?

故事扮演 提交于 2019-12-11 19:22:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!