我有一个函数,用于从数据库中选择要显示在表格中的数据。该函数正在生成一个无限循环。我该如何解决?
我的代码如下:
function view()
{
$db = new mysqli("localhost", "root", "", "blog");
$sql = 'SELECT * FROM news';
$result = $db->query($sql) or die($mysqli->error);
return $result->fetch_assoc();
}
?>
<table>
<tr>
<th scope="col">Title</th>
<th scope="col">Slug</th>
<th scope="col">Text</th>
</tr>
<?php while($row = view()) { ?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['slug']; ?></td>
<td><?php echo $row['text']; ?></td>
</tr>
<?php } ?>
</table>
谢谢。
最佳答案
试试这个:
function view()
{
$db = new mysqli("localhost", "root", "", "blog");
$sql = 'SELECT * FROM news';
$result = $db->query($sql) or die($mysqli->error);
$results=array();
while($row=$result->fetch_assoc())
$results[] = $row;
return $results;
}
?>
<table>
<tr>
<th scope="col">Title</th>
<th scope="col">Slug</th>
<th scope="col">Text</th>
</tr>
<?php $results = view();
foreach($results as $result_index=>$result_values) { ?>
<tr>
<td><?php echo $result_values['title']; ?></td>
<td><?php echo $result_values['slug']; ?></td>
<td><?php echo $result_values['text']; ?></td>
</tr>
<?php } ?>
</table>
关于php - Mysql select 查询/PHP 函数正在生成无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25817238/