0

我尝试使用嵌套的 foreach 插入输入字段数组。如果我为一个字段提供一个值,它工作正常,但如果我提供多个字段,则插入操作重复 8 次

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
  }

输入:

1.Make:cam 型号:mac 序列号:rak 2.Make:cam 型号:mac 序列号:dam

但得到的结果是输出

4

1 回答 1

1

尝试:

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);
}
于 2013-09-17T06:03:35.110 回答