【问题标题】:Inserting arrays into SQL with for loop使用 for 循环将数组插入 SQL
【发布时间】:2015-05-11 07:04:30
【问题描述】:

我在页面上有一个由 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>';

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

ID |装备列表 |舞台
ID 装备[] 舞台[]

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

【问题讨论】:

  • 编辑并删除不必要的html,唯一相关的是实际循环,您还应该改进代码的缩进,使其更易于阅读。
  • 很抱歉,但在过去,我因未提交代码而获得 6 票反对。我现在起飞
  • 只需使用一个循环并使用索引来访问两个数组。您可以使用sizeof 获取数组的大小,并且您可能希望在循环之前比较数组的大小
  • 数组的大小每次都相同
  • 您的标签错误:&lt;table ...&gt;&lt;tr&gt;&lt;form ..&gt;...&lt;/tr&gt;。它们没有正确匹配,&lt;form&gt; 不是 valid content&lt;tr&gt;

标签: php html mysql arrays foreach


【解决方案1】:
  $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();

   }

可以优化为在一个查询中获取所有值。

【讨论】:

  • 每一步都需要准备吗? :)
  • 您不应该在循环内调用prepare()bind_param(),只需在开始循环之前执行一次,即:$stage = null; $equip = null; $statement = $con-&gt;prepare("INSERT INTO ..."); $statement-&gt;bind_param('ss', $equip, $stage); for($i = 0; $i &lt; $length; $i++) { $stage = $stages[$i]; $equip = $equips[$i]; $statement-&gt;execute(); }
  • 这工作谢谢。必须更改一些特定于我的代码的位,但您不会知道这些。非常感谢您的帮助。
  • 我也接受了@cyclone 的建议,每次都调用它似乎不是一个好主意 - 如果它允许我,请支持它。我没有足够的积分来编辑 anwser,因为这是一个很好的观点
  • 这就是为什么我说它可以优化。我只是想展示如何更改在循环中也包含命令的当前代码。
【解决方案2】:
$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();
    }

【讨论】:

  • 这仍然包含将有n x n插入而不是n的错误
  • 他使用了两次foreach,因为他认为这是寻址两个数组的方式。但是,数组具有成对的值,每个数组中具有相同的数组索引。它们可以在一个foreach 中解决,创建 n 行发送到数据库。
猜你喜欢
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2012-02-18
相关资源
最近更新 更多