1

If I have a table in a MySQL DB, with fields id and position amung others.

Then in PHP I have an array like this:

Array
(
    [0] => 1
    [1] => 3
    [2] => 8
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)

Where the array key should map to the position and the array value should map to the id.

For example, If I made a call for every array value the first would be

UPDATE table SET position = 0 WHERE id = 1

Is there a way I could do all this in 1 call?

3 Answers 3

3
$string = "";
foreach($array as $k => $v)
 $string .= "UPDATE table SET position = ".$v." WHERE id = ".$k.";";
mysql_query($string);
Sign up to request clarification or add additional context in comments.

4 Comments

it make only 1 request to DB, this code simply loop through the array and create a string composed by more concatenate queries...
No! It only makes one call because the foreach has no brackets!
MySQL's PHP driver does not allow more than one query statement in any given query call. This construct will fail with a syntax error.
However this is not going to work this way cause you cannot include multiple statements at once using ; also += should change to .= because += is mathematical operation not string conncatenation.
1

updating multiple records with different values for each record is possible, but it's not recommdned - it makes for an incredibly ugly query:

UPDATE table
SET position = CASE position
    WHEN 0 THEN 1
    WHEN 1 THEN 3
    WHEN 2 THEN 8
    etc...

1 Comment

this sound very interesting. I am interested to know is there any other reason this is not recommended apart from being ugly?
0

Here we go a foreach solution :

$Array = array(0 => 1, 1 => 3);

if(count($Array) > 0){
    foreach($Array as $Key => $Value)
        // UPDATE table SET position = 1 WHERE id = 3 LIMIT 1
        mysql_query('UPDATE table SET position = '.$Key.' WHERE id = '.$Value.' LIMIT 1;');
}

Problem : you can't do multiple update with MySQL ... yes, like Marc B said but it's very ugly.

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.