我的代码有什么问题,数据使用准备从数据库中检索


What is wrong with my code that data retrieving from database using prepare

这是我使用 prepare 语句从数据库中检索数据的 PHP 代码

if ($conn) { //database connected success
$view_sql = "SELECT * FROM certificate_verify";
$stmt_view = $conn->prepare($view_sql);
$stmt_view->execute();
$results_view = $stmt_view->fetchAll();
foreach($results_view as $row) {
    $view_first_name = $row['first_name'];
    $view_last_name = $row['last_name'];
}

我需要从数据库中获取所有数据以显示在以下显示页面中

<table>
  <tr>
    <td><?php echo $view_first_name; ?></td>
    <td><?php echo $view_last_name; ?></td>
  </tr>
</table>

但我只得到最后一行数据(不是来自数据库的所有数据)为什么会发生这种情况以及我的代码有什么问题?

在表中使用 foreach 循环,

否则在 foreach 循环中数据 ovetlap,并且只得到最后一个值

<?php
$results_view = $stmt_view->fetchAll();
?>
<table>
    <?php foreach ($results_view as $row) { ?>// start your loop here
        <tr>
            <td><?php echo $row['first_name']; ?></td>
            <td><?php echo $row['last_name']; ?></td>
        </tr>
    <?php } ?>// loop end
</table>

foreach(...){...}代码替换为以下内容:

echo "<table>";
foreach ($results_view as $row)
{
  echo "<tr>";
  foreach ($row as $cell)
  {
    echo "<td>".$cell."</td>";
  }
  echo "</tr>";
}
echo "</table>";

显然,因为每次迭代foreach循环时,您的$view_first_name$view_last_name都会被来自$row的新值覆盖。您需要进行$view_first_name$view_last_name Array,并在tr上进行迭代。