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

PHP中如何从空MySQL游标创建默认变量避免报错

解决“Creating default object from empty value”报错的方案

问题根源是当查询无匹配行时,$row_c = $stmt_c->fetch(PDO::FETCH_OBJ)会返回null,此时在else分支直接给$row_c->subject等属性赋值,相当于试图给空值创建默认对象,因此触发警告。

核心解决方法

先将$row_c初始化为一个空的stdClass对象,再根据查询结果覆盖属性:

// 初始化空对象,预设默认值
$row_c = new stdClass();
$row_c->subject = "";
$row_c->textcontent = "";
$row_c->notes = "";

$query_c = "SELECT * FROM content WHERE `cid` = ".$_SESSION['cid'];
$stmt_c = $dbh->query($query_c);
$fetched_row = $stmt_c->fetch(PDO::FETCH_OBJ);

// 查询到结果时,覆盖默认值
if ($fetched_row) {
  $row_c->subject = str_replace("`","'",$fetched_row->subject);
  $row_c->textcontent = str_replace("`","'",$fetched_row->textcontent);
  $row_c->notes = str_replace("`","'",$fetched_row->notes);
}

额外优化建议

  1. 原代码中$rowcount变量未定义,直接用$fetched_row是否为真判断即可(fetch返回false/null表示无结果)。
  2. 直接拼接$_SESSION['cid']存在SQL注入风险,建议改用预处理语句:
$row_c = new stdClass();
$row_c->subject = "";
$row_c->textcontent = "";
$row_c->notes = "";

// 使用预处理语句避免SQL注入
$query_c = "SELECT * FROM content WHERE `cid` = ?";
$stmt_c = $dbh->prepare($query_c);
$stmt_c->execute([$_SESSION['cid']]);
$fetched_row = $stmt_c->fetch(PDO::FETCH_OBJ);

if ($fetched_row) {
  $row_c->subject = str_replace("`","'",$fetched_row->subject);
  $row_c->textcontent = str_replace("`","'",$fetched_row->textcontent);
  $row_c->notes = str_replace("`","'",$fetched_row->notes);
}

内容的提问来源于stack exchange,提问作者jack.linton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:40:38