user189643
user189643

Reputation:

help with php FOREACH loop

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

Upvotes: 0

Views: 1208

Answers (6)

Gucho Ca
Gucho Ca

Reputation: 682

Don't use mysql_query , its very insecure and is deprecated .

start using mysqli_query, is not as safe as PDO but will be lot better.

Upvotes: 0

Kamilos
Kamilos

Reputation: 805

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

Upvotes: 3

JW.
JW.

Reputation: 51678

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.

Upvotes: 0

Paul Tarjan
Paul Tarjan

Reputation: 50672

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

Upvotes: -1

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41326

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

Upvotes: 4

Marius
Marius

Reputation: 59009

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());
 }

Upvotes: 1

Related Questions