mysqli查询无结果致数组偏移访问报错的问题求助
解决PHP中mysqli_fetch_array返回null时访问数组偏移的报错问题
问题原因
当数据库查询无匹配结果时,mysqli_fetch_array()会返回null。原代码直接尝试访问$s_m_shape_2['next_review_date'],此时变量是null而非数组,因此触发Trying to access array offset on value of type null错误。
解决方案
核心思路是先判断查询结果是否有效(非null),再处理数组访问逻辑,同时初始化默认值避免后续报错。
修改后的关键代码如下:
$search_med_shape_2 = "select fs.shape_date,fs.shape_category,fd.next_review_date from force_shape_2 fs,force_shape_2_detail fd where fs.force_id='".$fid."' and fs.force_id=fd.force_id and fd.next_review_date<>'1970-01-01 00:00:00' order by shape_date desc limit 1"; $s_med_shape_2 = mysqli_query($connpis, $search_med_shape_2); $s_m_shape_2 = mysqli_fetch_array($s_med_shape_2, MYSQLI_ASSOC); // 处理查询结果为null的情况,初始化默认数组 if (!$s_m_shape_2) { $s_m_shape_2 = [ 'next_review_date' => '0', 'shape_date' => '', 'shape_category' => '' ]; } else { // 原有的空值处理逻辑 if ($s_m_shape_2['next_review_date'] == "") { $s_m_shape_2['next_review_date'] = '0'; } } $med_shape_1 = mysqli_num_rows($s_m_cat); $med_shape_2 = mysqli_num_rows($s_med_shape_2); // 后续逻辑可安全访问$s_m_shape_2的键 if ($med_shape_1 > '0' or $med_shape_2 > '0') { // 注意:需确保$s_med_cat不为null,否则会触发同类报错 if ($s_med_cat['shape_date'] > $s_m_shape_2['next_review_date']) { $ind_med_shape = $s_med_cat['code']." As On "; $ind_med_shape_date = date("d-m-Y",strtotime($s_med_cat['shape_date'])); } }
额外建议
原代码直接将$fid拼接进SQL语句,存在SQL注入风险,建议使用mysqli预处理语句替代,示例如下:
// 使用预处理语句避免SQL注入 $search_med_shape_2 = "select fs.shape_date,fs.shape_category,fd.next_review_date from force_shape_2 fs,force_shape_2_detail fd where fs.force_id=? and fs.force_id=fd.force_id and fd.next_review_date<>'1970-01-01 00:00:00' order by shape_date desc limit 1"; $stmt = mysqli_prepare($connpis, $search_med_shape_2); mysqli_stmt_bind_param($stmt, "s", $fid); mysqli_stmt_execute($stmt); $s_med_shape_2 = mysqli_stmt_get_result($stmt); $s_m_shape_2 = mysqli_fetch_array($s_med_shape_2, MYSQLI_ASSOC);
内容的提问来源于stack exchange,提问作者suman singh
相关产品推荐
相关产品推荐

