0

I tried inserting array of input fields with nested foreach.if i provide one value for one field it works fine but if i provide more than one field the inserting operation repeats for 8 times

PHP:

if ($_POST['fields']) {
  //get last inserted userid
  $inserted_user_id =mysql_insert_id(); 
  //Loop through added fields
  foreach ( $_POST['fields'] as $key=>$value ) {
    foreach ( $_POST['fields1'] as $key=>$value1 ) {
      foreach ( $_POST['fields2'] as $key=>$value2 ) {
        foreach ( $_POST['fields3'] as $key=>$value3 ) {
          $inserted_website_id = 1;
          //Insert into users_websites_link table
      $sql_users_website = sprintf("INSERT INTO users_websites_link 
        (UserID, CameraID,make, model ,serial,description2) VALUES
            ('%s','%s','%s','%s','%s','%s')",
            mysql_real_escape_string($inserted_user_id),
            mysql_real_escape_string($inserted_website_id),
            mysql_real_escape_string($value),
            mysql_real_escape_string($value1),
            mysql_real_escape_string($value2),
            mysql_real_escape_string($value3) );  
            $result_users_website = mysql_query($sql_users_website);
          }
        }
      }
    }
  }
  else {
    //No additional fields added by user
  }

Input:

1.Make:cam model:mac serial:rak 2.Make:cam model:mac serial:dam

but the result obtained isoutput

Dhwani
  • 7,484
  • 17
  • 78
  • 139
ra_sangeeth
  • 467
  • 3
  • 13
  • You have 4 loops, each of them will execute not only the amount of itself iterations, but as many times, as the surrounding loops are iterating. This is not unusual behavior. – Royal Bg Sep 17 '13 at 05:59
  • Please note that mysql_* functions are deprecated, and that you should be using mysqli_* functions or PDO. [Here is some more information.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php/60496#60496) – Steven Liao Sep 17 '13 at 06:01

1 Answers1

1

Try:

foreach ( $_POST['fields'] as $key=>$value ) {
    $value1 = $_POST['fields1'][$key];
    $value2 = $_POST['fields2'][$key];
    $value3 = $_POST['fields3'][$key];


    $inserted_website_id = 1;


    //Insert into users_websites_link table
    $sql_users_website = sprintf("INSERT INTO users_websites_link (UserID, CameraID,make, model ,serial,description2) VALUES ('%s','%s','%s','%s','%s','%s')",
                           mysql_real_escape_string($inserted_user_id),
                           mysql_real_escape_string($inserted_website_id),
                           mysql_real_escape_string($value),
                            mysql_real_escape_string($value1),
                            mysql_real_escape_string($value2),
                            mysql_real_escape_string($value3) );  
    $result_users_website = mysql_query($sql_users_website);
}
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89