我试图从数据库中获取并显示两个值“cat_name”和“cat_description”,并将它们显示在表中。据我所知,代码很好。 我对 PHP 还很陌生,几乎没有经验。
我尝试过很多问题,也尝试过很多可能的答案。我真的无法说出我尝试过多少次尝试来解决这个问题。
$query = $con->prepare("SELECT cat_id, cat_name, cat_description FROM categories");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(!isset($result))
{
//something went wrong, display the error
echo 'Error';
}
else
{
if($result == 0)
{
echo 'No categories defined yet.';
}
else
{
echo '<table border ="1">
<tr>
<th>Category</th>
<th>Last Topic</th>
</tr>';
var_dump($result);
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3><a href="category.php?id">' . $row['cat_name'] . '</a></h3>' . $row['cat_description'];
echo '</td>';
echo '<td class="rightpart">';
echo '<a href="topic.php?id=">Topic subject</a> at 10-10';
echo '</td>';
echo '</tr>';
}
}
}
我应该期待一个显示两列的表格,其中一列显示类别(超链接),并带有从数据库中获取的类别的简短描述。还有另一列该类别中的主题,但到目前为止还没有达到这一点。
预期结果:
当我运行这段代码时,我似乎得到的只是一个错误。
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given
最佳答案
一旦你跑了
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$result
将是查询中记录的数组,因此当您到达
while($row = mysqli_fetch_array($result)){
您已经拥有数据,因此 $result
不是结果集,而是数据数组。因此,您可以将此行替换为...
foreach ( $result as $row ) {
关于php - mysqli_fetch_array() 期望参数 1 为 mysqli_result,给出 PHP 论坛尝试的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55678622/