You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移至新版PHP后博客编辑器出现数组偏移访问警告的解决求助

解决PHP数组偏移访问警告的方案

问题原因

新版PHP对类型校验更严格,当$stmt3->fetch()未查询到匹配数据时,会返回布尔值false而非空数组。此时直接访问$row3['catID']就会触发Trying to access array offset on value of type bool警告。

快速修复方案

方案1:先判断$row3的类型

修改原代码中的判断逻辑,先确认$row3是数组再访问其键值:

// 替换原if语句
if(is_array($row3) && $row3['catID'] == $row2['catID']){
    $checked = 'checked=checked';
} else {
    $checked = null;
}

方案2:用rowCount()判断是否存在匹配记录

无需获取查询结果,直接通过rowCount()判断是否有匹配的关联记录:

// 替换原$row3 = $stmt3->fetch();及后续if语句
$stmt3->execute(array(':catID' => $row2['catID'], ':postID' => $row['postID']));
if($stmt3->rowCount() > 0){
    $checked = 'checked=checked';
} else {
    $checked = null;
}

性能优化建议(可选)

原代码在循环中多次执行数据库查询,效率较低。可以一次性查询当前文章关联的所有分类ID,再循环判断:

<legend>Categories</legend>

<?php
// 先查询当前文章关联的所有分类ID
$stmt_post_cats = $db->prepare('SELECT catID FROM blog_post_cats WHERE postID = :postID');
$stmt_post_cats->execute(array(':postID' => $row['postID']));
$post_cats = [];
while($cat_row = $stmt_post_cats->fetch()){
    $post_cats[] = $cat_row['catID'];
}

// 查询所有分类并渲染复选框
$stmt2 = $db->query('SELECT catID, catTitle FROM blog_cats ORDER BY catTitle');
while($row2 = $stmt2->fetch()){
    $checked = in_array($row2['catID'], $post_cats) ? 'checked=checked' : null;
    echo "<input type='checkbox' name='catID[]' value='".$row2['catID']."' $checked> ".$row2['catTitle']."<br />";
}
?>

内容的提问来源于stack exchange,提问作者SG-17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 06:37:18