0

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?

2
  • 1
    "331,554,22" - is this really an array, or is it a string of numbers separated by commas? If it is the latter, you will need to explode() it first, then you will have an array. Just asking. Commented Nov 22, 2011 at 1:27
  • its a string, so, yeah explode i guess. Commented Nov 22, 2011 at 1:28

4 Answers 4

2

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})"
Sign up to request clarification or add additional context in comments.

Comments

1
foreach($numbers as $number) {
  $sql = "UPDATE some_table SET X = 1 WHERE id = ".$number
}

Hope it helps

Comments

0
$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})";

Comments

0
<?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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.