如何才能在数据库中保存1次

时间:2017-11-05 07:31:59

标签: php mysql database

$ctr = 0;
foreach($_POST['field_name'] as $key => $field_name)
   foreach($_POST['field_name1'] as $key => $field_name1)
   {
{
   if($_POST['field_name'][$key]){
      if($_POST['field_name1'][$key]){
      $sqli = "INSERT INTO farmersform (IDTwo,IDThree,IDFour,FCrops,FLandArea) VALUES ('$IDTwo','$IDThree','$IDFour','$field_name','$field_name1')";
      $result = $conn->query($sqli);
      if($result){
         $ctr++;
      }
   }
}

} }

这是我的代码,如果它保存,它会在数据中保存2个类似的数据,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

删除其中一个foreach循环。假设field_namefield_name1具有相同的数组长度,您的代码仍然可以进行一些调整。

$ctr = 0;
foreach($_POST['field_name1'] as $key => $field_name1) {
  if ($_POST['field_name'][$key]) {
    if ($_POST['field_name1'][$key]) {
      $sqli = "INSERT INTO farmersform (IDTwo,IDThree,IDFour,FCrops,FLandArea) VALUES ('$IDTwo','$IDThree','$IDFour','{$_POST['field_name'][$key]}','$field_name1')";
      $result = $conn->query($sqli);
      if ($result) {
        $ctr++;
      }
    }
  }
}