[web] Looping through $_POST?

Started by
1 comment, last by leiavoia 15 years, 3 months ago
Hello I'm new to PHP, and having a little trouble with the following code.

for($i = 0; $i < $noOfRecords; $i++){
    $sql = "INSERT INTO tblTest (fldSupplier, fldCodes, fldPrice)
    VALUES ('".$_POST[$count] ."', '".$_POST[$count+1]."', '".$_POST[$count+2]."')";
		
    if(!mysql_query($sql, $con)){
	echo("Error with SQL Statement");
	die("Error with SQL statement");
    }
    $count = $count + 3;
    }


I know how many elements are in the array, but it's not putting the values from the various array elements into the table. I've tested to make sure that the values are being sent by using the $_POST key E.G $_POST[rec1Sup] and this works, but when I try to loop through the array it inserts blank strings. Any help would be appreciated. I've sending it the following values rec1sup = "Supplier A" rec1code = "555-12345" rec1price = "23" ... rec4sup = "Supplier C" rec4code = "555-12345" rec4price = "213"
Advertisement
Quote:Original post by natebuckley
Hello I'm new to PHP, and having a little trouble with the following code.


Believe me, you're going to have a lot of trouble : SQL injection.

Either way, foreach.
I agree with ToohrVyk about the SQL injection. You'll need to sanitize everything nicely first if this is not just a learning excercise.

When you have these sorts of grouped-inputs, you have to get creative with the HTML naming so that you can search for them later. All you records start with "rec#", so that works. Keep in mind that there may be other crud in your POST besides just those records though, including hidden form elements. Also keep in mind that PHP won't return certain form variables if they are blank (checkboxes). You definately don't want to rely on a simple counter to loop through the POST array. Never assume the data is in the condition you want.

First extract all the records you actually want using something like preg_match and put those into a new associative array. Then do something like this:
for ( $i=0; $i < $max; $i++ ) {   // make sure we have all three   if ( !isset( $array["rec{$i}sup"] ) ||      !isset( $array["rec{$i}code"] ) ||      !isset( $array["rec{$i}price"] )      ) {      /* incomplete data - major bother */      continue; // skip this one      }      $sup = $array["rec{$i}sup"];   $code = $array["rec{$i}code"];   $price = $array["rec{$i}price"];   // do query here using above variables   }


That's the basic idea with no error checking, empty checking, or hack-attempt checking.

This topic is closed to new replies.

Advertisement