Re: Foreach

From: Date: Fri, 18 Jan 2008 17:03:38 +0000
Subject: Re: Foreach
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-267569@lists.php.net to get a copy of this message
On Jan 18, 2008 11:38 AM, Wolf <lonewolf@nc.rr.com> wrote: > Steve, > > This should work as some basic sudo code. You are running into a number of issues with your > usage of the foreach as it sounds like what you really want to do is walk through one array and grab > the corresponding value from another. > > <?php > // First check to make sure you are getting both fields > if(isset($_POST['name']) && is_array($_POST['name']) && > isset($_POST['order']) && is_array($_POST['order'])) > { > // Now assign them to easier to play with variables > $names=$_POST['name']; > $orders=$_POST['orders']; > // This tests for the same number of items as names > if (count($names) == count($orders)) > { > $i=0; > while($i<=count($names)) > { > $update_data = "UPDATE sections SET order = > '$orders[$i]' WHERE name = '$names[$i]'"; > $response = mysql_query( $update_data, $cnx ); > if(mysql_error()) die ('database error<br>'.mysql_error()); > } > } > } > ?> > > HTH, > Wolf > > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > > Hi Wolf, Your code is missing data validation! Hopefully you don't do stuff like that either. function super_duper_escaper($value, $db) { if (!get_magic_quotes_gpc()) { $value = mysql_real_escape_string($value, $db); } return $value; } $_sql = "UPDATE sections SET order = %d WHERE name = '%s'"; $sql = sprintf( $_sql, (int)$orders[$i], super_duper_escaper($names[$i], $cnx) ); What we're doing here is making sure that the order is a number and that the name is a string that properly escapes out the quotes to make sure people can't break out of the context of data and into commands. Look up SQL injection for more information. Don't rely on magic quotes, etc as it is a server specific setting, is going away in php6, and does not take character sets into consideration. The mysql extension is just as bad as it wont allow you to update the character set context from the mysql server default. So use mysqli or pdo unless everything matches across the board.

« previous php.general (#267569) next »