[英]What is wrong with my code that data retrieving from database using prepare
this is my php code for retrieving data from database using prepare statement 这是我的php代码,用于使用prepare语句从数据库检索数据
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'];
}
I need to fetch all data from database to display in the following display page 我需要从数据库中获取所有数据以在以下显示页面中显示
<table>
<tr>
<td><?php echo $view_first_name; ?></td>
<td><?php echo $view_last_name; ?></td>
</tr>
</table>
but I am getting only last row data (not all data from database) why it is happening and what is wrong with my code? 但是我只得到最后一行数据(不是数据库中的所有数据),为什么会发生,代码有什么问题?
Use foreach loop inside your table as otherwise you data ovetlap inside foreach loop and you get only last value 在表内使用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>
replace your foreach(...){...}
code with this: 用以下代码替换您的foreach(...){...}
代码:
echo "<table>";
foreach ($results_view as $row)
{
echo "<tr>";
foreach ($row as $cell)
{
echo "<td>".$cell."</td>";
}
echo "</tr>";
}
echo "</table>";
Obviously, Because every time you iterate your foreach
loop, your $view_first_name
and $view_last_name
get overwritten with new values coming from $row
. 显然,因为每次迭代foreach
循环时, $view_first_name
和$view_last_name
都会被$row
新值覆盖。 You need to make $view_first_name
and $view_last_name
Array
and iterate those over tr
. 您需要制作$view_first_name
和$view_last_name
Array
并遍历tr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.