将POST数组插入mySql表的多行时出现问题

时间:2019-03-30 22:45:33

标签: php mysql prepared-statement

我有一个将高尔夫球场记分卡输入数据库的表格

<table class="table table-bordered text-center table-striped">
<col style="width:15%">
<col style="width:20%">
<col style="width:20%">
<col style="width:20%">

<thead >
<tr>
  <th>Hole</th>
  <th>Yards</th>
  <th>Par</th>
  <th>SI</th>
    </tr>
</thead>

<tbody>
<?php

      for ($i = 1; $i <= 2; $i++) {
        echo 
    "<tr>

    <td ><input type='number' class='form-control' 
    name='holeNumber[]' id='hole".$i."iD' value=".$i." readonly> 
    </td>


    <td ><input type='number' class='form-control' 
    name='holeYards[]' id='hole".$i."yards'  ></td>


    <td ><input type='number' class='form-control' name='holePar[]' 
    id='hole".$i."par'  ></td>


    <td ><input type='number' class='form-control' 
    name='holeStrokeIndex[]' id='hole".$i."strokeIndex'  ></td>

</tr>";
}
    ?>

    </tbody>
    </table>

我仅将其设置为显示2行以便于测试

该表单以4个数组正确提交了我需要的数据,现在我需要将它们放入2个单独的行中。

mySql代码是

 $holeNumber = $_POST['holeNumber'];
 $yards = $_POST['holeYards'];
 $par = $_POST['holePar'];
 $strokeIndex = $_POST['holeStrokeIndex'];

    $sqlHoles = "INSERT INTO holes (courseId, holeNumber, yards, 
                 par, strokeIndex) VALUES (?, ?, ?, ?, ?)";


      if($stmtHole = mysqli_prepare($link, $sqlHoles)){

  // Bind variables to the prepared statement as parameters
      for ($i=0; $i<=1 ; $i++){

*   $holeNumber = $holeNumber[$i];
*   $yards      = $yards[$i];
*   $par        = $par[$i];
*   $strokeIndex= $strokeIndex[$i];

    mysqli_stmt_bind_param($stmtHole, "iiiii", $holeNumber, 
           $yards, $par, $strokeIndex);

}


   if(mysqli_stmt_execute($stmtHole)){
    echo "holes added to database.";
    } else{
    echo "ERROR: Could not execute query: $sqlHoles. " . 
    mysqli_error($link);
    }
    } else{
         echo "ERROR: Could not prepare query: $sqlHoles. " . 
      mysqli_error($link);
     }

我目前正在获得

未初始化的字符串偏移:1个错误

与标有*的行有关。

我意识到这与阵列有关,并且花了很长时间在网上寻找答案,但是我迷失了自己需要做的事情!

1 个答案:

答案 0 :(得分:1)

执行$holeNumber = $holeNumber[$i];时,将重新初始化变量并将其从数组更改为整数。只需将$ holeNumber更改为新变量$ intHoleNumber或其他内容即可。 (当然还有其他变量)。然后在bind函数中使用新变量。