Re: Foreach

From: Date: Fri, 18 Jan 2008 04:07:49 +0000
Subject: Re: Foreach
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-267525@lists.php.net to get a copy of this message
On 1/17/08, mike <mike503@gmail.com> wrote: > On 1/17/08, Nathan Nobbe <quickshiftin@gmail.com> wrote: > > > > $name = $_POST['name']; > > > if ($name) { > > > foreach ($name as $t) { > > > > > > echo "$t"; > > > } > > > > $order = $_POST['order']; > > > if ($order) { > > > foreach ($order as $i) { > > > > > there are a few different issues here; first of all; are you sure > > $_POST['name'] > > and $_POST['order'] are even arrays? > > hint: > > if(isset($_POST['name']) && is_array($_POST['name'])) Steve, // Do you have several html form elements such as <input type="text" name="name[]"> in your html? // Mike's suggestion... if( isset( $_POST['name'] ) && is_array( $_POST['name'] ) ) { // you'll never get in here if you don't... $name = $_POST['name']; // foreach expects an array, as Nathan states. Even if $name is an array, $t // will hold only the last value in the array when the foreach loop is exited // because $t is being overwritten with each iteration. foreach ($name as $t) { echo "$t"; } // end foreach ($name) $order = $_POST['order']; if ($order) { // see above about arrays and foreach foreach ($order as $i) { //Update the table in MySQL $i = mysql_real_escape_string($i, $cnx); // One of Eric's suggestions $update_data = "UPDATE sections SET order = '$i' WHERE name = '$t'"; $response = mysql_query( $update_data, $cnx ); if(mysql_error()) die ('database error<br>'. mysql_error()); echo "$i"; } //end foreach ($order) } } Assuming both $_POST['name'] and $_POST['order'] are arrays, the way your code is now structured, the table sections will have the record(s) where name equals the last value in the $names array updated multiple times, once for each value in the $order array, but all you will see is that the record(s) will have the last value in the $order array. See if this makes any sense and then ask more questions. David

« previous php.general (#267525) next »