PDO foreach循环不起作用

我是PDO的新手,在这里找不到我要解决的问题的答案。
我能运行foreach没有在桌子上环WHERE条款,但是当我将它复制一个类似的表一个WHERE条款,它没有返回数据!

这是无效的代码。我什至试图在没有ORDER BYLIMIT参数的情况下运行它,但还是没有运气!请指导。

<div class="table-responsive">
    <table class="teachers_profile_table table table-bordered">
         <thead>
             <th style="width:20%">Student</th>
             <th>Comment</th>
         </thead>
         <tbody>
<?php
$pdo = Database::connect();
<?php
$sql = "SELECT * FROM tbl_st_comments_abt_tut WHERE tut_id=?";
$q = $pdo->prepare($sql);
$q->execute(array($teacher_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
foreach ($pdo2->query($sql) as $row) {
    echo '<tr>';
    echo '<td>'.$row['st_name'].$row['input_date'].'</td>';
    echo '<td>'.$row['st_comment'].'</td>';
    echo '</tr>';
}
Database::disconnect();
?>
         </tbody>
    </table>
</div>

这是db表:表名称:tbl_st_comments_abt_tut id tut_id st_id st_name st_comment input_date(出于测试目的,我已在表中手动输入了3行)。

大规模可可

我不确定您要用此行实现什么:foreach ($pdo2->query($sql) as $row)我什至不确定它是否合法,$ pdo2是从哪里来的?

如果您遵循您的常识博客文章,您将发现您的foreach位于正确的位置,在显示结果之前检查是否获得结果也很重要。

您的代码应如下所示:

<div class="table-responsive">
         <table class="teachers_profile_table table table-bordered">
              <thead>
              <th style="width:20%">Student</th>
              <th>Comment</th>
              </thead>
              <tbody>
<?php
$pdo = Database::connect();


$sql = "SELECT * FROM tbl_st_comments_abt_tut WHERE tut_id= ? ";
$q   = $pdo->prepare($sql);
$q->execute([$teacher_id]);
$data = $q->fetchall(PDO::FETCH_ASSOC);

if (count($data) > 0) {

    foreach ($data as $row) {
        echo '<tr>';
        echo '<td>' . $row['st_name'] . $row['input_date'] . '</td>';
        echo '<td>' . $row['st_comment'] . '</td>';
        echo '</tr>';
    }
} else {

    echo "no results";
}

Database::disconnect();
?>
                </tbody>
         </table>
</div> 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章