Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/MYSQL: batch update multiple values

I have figured out how to do a batch update when the value is the same for each record using:

UPDATE tbl SET col1='foo1' WHERE id IN (1,2,3)

If I have a comma delimited string of values, that match up to the ids, can I do a batch update that updates the values differently as in

UPDATE tbl SET col1='1,0,1' WHERE id IN (1,2,3)

Thanks for suggestions:

Edit:

The html page that sends the data to this query consists of checkboxes as follows:

<input type="checkbox" name="id[]" value="1"><input type="hidden" name="col1[]" value=0> 
<input type="checkbox" name="id[]" value="2"><input type="hidden" name="col1[]" value=1>
<input type="checkbox" name="id[]" value="3"><input type="hidden" name="col1[]" value=0>

etc. up to 20 boxes.

On the server side, the posted arrays are converted to comma delimited strings using implode so I end up with the two strings, 1,0,1 for the values and 1,2,3 for the ids. But the user could check up to 20 boxes from this page. Maybe I have to manipulate the arrays somehow. Note in the real example, the ids are not 1,2,3, but could be something like 221, 433, 512, 600 etc., depending on what user checks

like image 257
user1260310 Avatar asked Jul 29 '26 02:07

user1260310


1 Answers

the second query will update each row 1, 2,3 to the same value '1,0,1'

i think what you need is

  UPDATE mytable
    SET myfield = CASE other_field
        WHEN 1 THEN 'value'
        WHEN 2 THEN 'value'
        WHEN 3 THEN 'value'
    END 
WHERE id IN (1,2,3) 

reference http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/

like image 73
Bakly Avatar answered Jul 30 '26 21:07

Bakly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!