我有一个可以访问数据库的“评论”表的代码。我做了一个连接变量并创建了所有东西以获取表。但是我在保存和刷新页面时,在下面显示此错误。有什么问题吗?
<?php
// connection
$connection = mysqli_connect(
$config['db']['server'],
$config['db']['username'],
$config['db']['password'],
$config['db']['name']
);
if ($connection == false)
{
echo 'Error!<br>';
echo mysqli_connect_error();
exit();
}
// comments
$сomments = mysqli_query($connection, "SELECT * FROM `comments` ORDER BY `articles_id` DESC LIMIT 5");
while ($com = mysqli_fetch_assoc($comments))
{
?>
<article class="article">
<div class="article__image" style="background-image: url(https://www.gravatar.com/avatar/<?php echo md5($com['email']); ?>?s=125);"></div>
<div class="article__info">
<a href="/article.php?id=<?php echo $com['articles_id']; ?>"><?php echo $com['author']; ?></a>
<div class="article__info__preview"><?php echo mb_substr(strip_tags($com['text']), 0, 100, 'utf-8') . ' ...'; ?></div>
</div>
</article>
<?php
}
?>
警告:mysqli_fetch_assoc()期望参数1为mysqli_result,在第56行的W:\ domains \ itblog.kg \ includes \ sidebar.php中给出null。有什么问题吗?
答案 0 :(得分:0)
问题是查询($comments = mysqli_query(...
)返回空值。这意味着查询存在一些问题。
尝试像这样更改代码:
$сomments = mysqli_query($connection, "SELECT * FROM `comments` ORDER BY `articles_id` DESC LIMIT 5");
// start new
if (!$comments) {
echo "Error - " . mysqli_error($connection);
} else
// end new
while ($com = mysqli_fetch_assoc($comments))
{
?>
<article class="article">
...
(请注意,您还应该用括号{}
包围整个while循环,因为它是else
子句,以避免将来出现错误。但是应该这样工作。)
该脚本应报告所看到的错误,并应允许您修复查询。
编辑-我敢打赌comments
表中没有articles_id
列-可能应该是article_id
。