使用 for 循环将数组插入 SQL


Inserting arrays into SQL with for loop

我在页面上有一个由 for 循环创建的表单。

$scripte = ($_POST["scriptake"]);
$scriptot = ($_POST["scriptot"]);
include 'config.php';
echo '<h2>'.$scripte.' Equipment</h2>';
echo '<h2>Total Hours '.$scriptot.'</h2>';
echo '<table class="table table-responsive">
        <tr>
          <form action="equiptest.php" method="post">
          <th>Script Hour</th>
          <th>Equipment Required</th>
          <th>Stage</th>
        </tr>';
$x = 1;
$p = 1;
$r = 1;
while($x <= $scriptot ) {
  echo "<tr>
          <td>".$x++."</td>
          <td>
            <input name='equip[".$r++."]'>
          </td>
          <td>
            <input name='stage[".$p++."]'>
            <input name='ohyeah' type='hidden' value= '".$scriptot."'>
          </td>
        </tr>";
}
echo '<tr>
        <td colspan="2">
          <input type="submit" class="btn btn-primary">
        </td>
      </tr>
      </form>
     </table>';

如您所见,带有输入的表单是使用 for 循环创建的。表单中的值收集在数组 equip[] 和 stage[] 中。如果有意义的话,有一个索引计数器。然后将表单提交到以下脚本。

include 'config.php';
$scriptot = ($_POST["ohyeah"]);
$y = 1;
$r= 1;
foreach($_POST['equip'] as $key => $value) {    
  foreach($_POST['stage'] as $key => $stage) {
    $query = $con->stmt_init();
    $statement = $con->prepare("INSERT INTO dgam_equip 
                                (equiplist,stage)  VALUES (?,?)");
    $statement->bind_param('ss',$value,$stage);
    $statement->execute();
  }
}
echo 'success';
//bind result variables to be printed
$statement->close();
echo '<br><br><br><br><br>';

然后我正在尝试将数组插入数据库。

身份证 |装备师 |阶段
身份证装备[] 阶段[]

我正在尝试嵌套一个 foreach 循环或将数组添加到正确的行中。我可以把行放进去,但数据会超过很多次。我猜这是因为 foreach 循环正在执行第二个 foreach 循环将此类数据放入数据库的正确方法是什么。我正在尝试先设置一个阵列,但正在挣扎。

  $length = count($_POST['stage']);
  $stages = $_POST['stage'];
  $equips = $_POST['equip'];
  $stage = '';
  $equip = '';
  $query = $con->stmt_init();
  $statement = $con->prepare( "INSERT INTO dgam_equip (equiplist,stage)  VALUES (?,?) ");
  $statement->bind_param('ss', $equip, $stage);
  for( $i=0; $i < $length; $i++ ) {
     $stage = $stages[$i];
     $equip = $equips[$i];
     if ( ! empty($stage) ) $statement->execute();
   }

可以对其进行优化以在一个查询中获取所有值。

$equipes = $_POST['equip'];
$stages = $_POST['stage'];
$query = $con->stmt_init();
$statement = $con->prepare( "INSERT INTO dgam_equip (equiplist,stage)  VALUES (?,?) ");
for ($i = 0, $total = count($equipes); $i < $total; $i = $i + 100) {
        $insertEquipe = array_slice($equipes, $i, 100);
        $insertStage = array_slice($stages, $i, 100);
        $conn->beginTransaction();
        foreach ($insertEquipe as $equipe) {
           foreach ($insertStage as $stage) {
               $stmt->bindValue(1, $equipe);
               $stmt->bindValue(2, $stage);
               $stmt->execute();
            }  
        }
        $conn->commit();
    }