在写一个项目的时候,出现了"Warning: Illegal string offset"的警告报错信息,翻译过来:非法字符串偏移。
原因是:$postArr数组在遍历时发生错误,未加上[],导致空数组里没有"name"、"title"等字段。
'''
<?php
require_once 'config.php';
//最新发布的功能
//1、连接数据库
//2、查询文章信息
//3、动态生成结构
$connect = mysqli_connect("localhost","root","root","baixiu");
$sql = "SELECT p.title,p.created,p.content,p.views,p.likes,p.feature,c.name,u.nickname,
(SELECT count(id) FROM comments WHERE post_id = p.id) as commentsCount
FROM posts p
LEFT JOIN categories c on c.id=p.category_id
LEFT JOIN users u on u.id=p.user_id
WHERE p.category_id != 1
ORDER BY p.created DESC
LIMIT 5";
$postResult = mysqli_query($connect,$sql);
//转化为二维数组遍历
$postArr = [];
while($row = mysqli_fetch_assoc($postResult)){
$postArr[]= $row;
}
// print_r($postArr);
?>
网友评论