-1

With this update query if the id is in chk_list then I set checked=1. I want if the id isn't in the list to set chk_list=0

$update = "UPDATE data SET checked=1 WHERE id IN($chk_list)";

$qry = $db->query($update);

Is there any simple way after WHERE to set if?

David Walschots
  • 12,279
  • 5
  • 36
  • 59
  • You can simply set the default value of the field to 0! – Mostafa Kasem Sep 24 '18 at 18:18
  • 1
    Can't you just do `NOT IN`? https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_not-in – user3783243 Sep 24 '18 at 18:19
  • 1
    Either of the 2 answers will work. I'm curious though, why do you want to update every record on a table? I've never seen a scenario like this – dustytrash Sep 24 '18 at 18:20
  • Hi Raul, could you clarify your question? Perhaps add some context as to what you're trying to achieve on your table. – Lex Sep 24 '18 at 23:09

3 Answers3

2

You can use IF() function to determine value to be set. Do the following:

$update = "UPDATE data SET checked = (IF(id IN ($chk_list), 1, 0))";
$qry = $db->query($update);

Note: Please use Prepared Statements to prevent SQL injection related issues

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
1

If you want to explicitly set checked as 1 or 0, then the if should be in the set area Notice that its very dangerous to update all of the table to the extent that MySQL by default prevents this from happening, ans you should set safe updates to 0

UPDATE data SET checked = IF(id IN ($chk_list), 1,0)
Guy Louzon
  • 1,175
  • 9
  • 19
1

What about this with CASE? Not sure pretty neat or not but seems it'll work :)

UPDATE data SET checked= 
CASE
  WHEN id IN ($chk_list) THEN 1
  WHEN id NOT IN ($chk_list) THEN 0
END
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103