tags:

views:

443

answers:

5

hi, can some please tell me what's wrong with the bellow foreach php loop.

foreach ($_POST[sortlist] as $key => $value) 
{
    $sql = "UPDATE sortable 
            SET color_order = " . mysql_real_escape_string($key) . " 
            WHERE id = " . mysql_real_escape_string($value);

    $result = mysql_query($sql) or die(mysql_error());
}

I keep getting warning: invalid argument suplied foreach() in .... when i upload to server

Thanks

+1  A: 

I'm assuming that $_POST[sortlist] is not an array. This is probably what you are trying to do:

foreach ($_POST as $varname => $varvalue) {
    $sql = "update sortable set color_order = ".mysql_real_escape_string($varname)."   where id = ".mysql_real_escape_string($varvalue);
    $result = mysql_query($sql) or die(mysql_error());
 }

Or if $_POST['sortlist'] is an array, try this:

foreach ($_POST['sortlist'] as $varname => $varvalue) {
    $sql = "update sortable set color_order = ".mysql_real_escape_string($varname)."   where id = ".mysql_real_escape_string($varvalue);
    $result = mysql_query($sql) or die(mysql_error());
 }
Marius
+4  A: 

$_POST['sortlist'] is probably not an array. Try print_r($_POST) to see what do you have there.

Lukáš Lalinský
+3  A: 

Try change $_POST[sortlist] to $_POST['sortlist'];

Kamilos
A: 

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Paul Tarjan
A: 

A tip: the error message refers to the foreach line. That only reads from one variable, $_POST[sortlist], which isn't modified inside the loop. So you can ignore all the SQL stuff; it's not relevant to your problem. Reduce the problem to the smallest possible piece of code that still has an error. That will help you solve it.

JW