【问题标题】:foreach loop duplicates values php sqlforeach循环重复值php sql
【发布时间】:2023-03-17 07:05:02
【问题描述】:

为什么这个双 foreach 循环重复值

 foreach($_POST['studentpoints'] as $value) {
        foreach($_POST['studentids'] as $valor) {
            $stmt->bindParam(':studentid', $studentids);
            $stmt->bindParam(':studentpoints', $points);
            $studentids = $valor; 
            $points = $value;
            $stmt->execute();
        }

此代码不重复值,而只读取学生的第一个 id

foreach($_POST['studentpoints'] as $value) { 
        foreach($_POST['studentids'] as $valor) {
           $studentids = $valor;
        }

   $stmt->bindParam(':studentid', $studentids);
            $stmt->bindParam(':studentpoints', $points);
            $studentids = $valor; 
            $points = $value;
            $stmt->execute();

}

数据库中的数据表

<?php foreach($rowstudents as $row): ?>
  <tr>
    <th><input type="hidden" name="studentids[]" value="<?php echo ' ' . htmlentities($row['studentid'], ENT_QUOTES, 'UTF-8') . ' ';?>" />
    <?php echo '' . htmlentities($row['studentid'], ENT_QUOTES, 'UTF-8') . '';?></th>  
    <th><?php echo '' . htmlentities($row['fname'], ENT_QUOTES, 'UTF-8') . '';?></th>
    <th><?php echo '' . htmlentities($row['lname'], ENT_QUOTES, 'UTF-8') . '';?></th> 
    <th><input type="text" name="studentpoints[]" value="<?php echo '' . htmlentities($row['studentpoints'], ENT_QUOTES, 'UTF-8') . '' ?>"></th>
  </tr>
<?php endforeach; ?>
</table>

【问题讨论】:

  • 这就是为什么你在调用双重 foreaches
  • 这两个循环可以合二为一吗?
  • 我可能会创建某种包含整行的student 对象。然后,您只需遍历学生并提取相关信息。除此之外,您需要一个for 循环来获取索引——这需要更多的错误检查。为什么你不能只做$stmt-&gt;bindParam(':studentid', $valor);(虽然这不能解决你的重复问题)?
  • @Clockwork-Muse 是的,我尝试过,但我仍然得到重复

标签: php html css sql


【解决方案1】:

您正在使用 for each 循环两次。除此之外似乎没有任何问题

【讨论】:

  • 是的,我看到了:/我想要做的是将这两个循环合并为一个
【解决方案2】:
   for ($i=0; $i<count($_POST['studentpoints']); $i++) {
           $studentids = $_POST['studentid'][$i]; 
           $points = $_POST['studentpoints'][$i];

           $stmt->bindParam(':studentid', $studentids);
           $stmt->bindParam(':studentpoints', $points);
           $stmt->execute();

   }

【讨论】:

  • 谢谢,我正在尝试这个,但它给出了警告警告:非法字符串偏移 'studentid' in 和错误致命错误:只有变量可以通过引用传递
  • 再次感谢您,但现在出现不同的错误 Error 1 SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'studentid' cannot be null
  • 如果想看看我在尝试什么,我会修改我的问题
  • 编辑了我的方法,尝试新的方法。
  • 嗯...这是有效的,但是对于将 singular id 保持为复数形式的变量存在一些误导性:studentids.
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多