PDO foreach循环不起作用

时间:2017-01-13 08:56:42

标签: php 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行。)

1 个答案:

答案 0 :(得分:0)

我不确定你想用这条线做什么: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>