Reputation: 13651
I have an array which contains numbers like "331,554,22" or it could be "45", lets say the array is called $numbers
.
I want to loop through the array and for each number or entry in it, do a SQL query like
UPDATE members SET x=1 where id=$numbers[x]
Could someone help me along?
UPDATE: Also, say I store the query values in a text field in my database called nums
and it looks like eg. "45,656,23", how would I convert that to an array format?
Upvotes: 0
Views: 146
Reputation: 3962
if the veriable "331,554,22"
is not an array (string),
explode it first
$numbers = explode(',',$numbers);
and then.
Foreach :
foreach ($numbers as $number)
{
//query like SET x=1 where id=$number
}
For :
for($i = 0; $i < count($numbers); $i++)
{
//query like SET x=1 where id=$numbers[$i]
}
if x is always 1 you can use in,
$query = "UPDATE table SET x = 1 WHERE id IN(" . implode(',',$numbers) . ")"
and if the $numbers
variable is string, and x
will be 1
for each ID, forget all of I wrote and try this only :)
$query = "UPDATE table SET x = 1 WHERE id IN({$numbers})"
Upvotes: 2
Reputation: 10258
<?php
$numbers = array(25, 658, 968, 548, 698, 365);
foreach($numbers as $number){
echo "UPDATE members SET x=1 where id=$number\n";
}
?>
OUTPUT
UPDATE members SET x=1 where id=25
UPDATE members SET x=1 where id=658
UPDATE members SET x=1 where id=968
UPDATE members SET x=1 where id=548
UPDATE members SET x=1 where id=698
UPDATE members SET x=1 where id=365
Upvotes: 0
Reputation: 140236
$query = "UPDATE members SET x=1 WHERE id IN(".implode( ",", $numbers).")";
its a string, so, yeah explode i guess.
$query = "UPDATE members SET x=1 WHERE id IN({$numbers})";
Upvotes: 0
Reputation: 100195
foreach($numbers as $number) { $sql = "UPDATE some_table SET X = 1 WHERE id = ".$number }
Hope it helps
Upvotes: 1