CodeIgniter项目运行时出现Undefined property: stdClass::$cancelled警告错误
CodeIgniter项目「Undefined property: stdClass::$cancelled」警告解决
错误详情
PHP错误已遭遇
级别:警告
信息:Undefined property: stdClass::$cancelled
文件名:transactions/transtable.php
行号:38
回溯信息
- 文件:
C:\xampp\htdocs\mini-inventory-and-sales-management-system\application\views\transactions\transtable.php,行号38,函数_error_handler - 文件:
C:\xampp\htdocs\mini-inventory-and-sales-management-system\application\controllers\Search.php,行号103,函数view - 文件:
C:\xampp\htdocs\mini-inventory-and-sales-management-system\index.php,行号315,函数require_once
报错位置代码片段
<?php foreach($allTransactions as $get): ?> <tr> <th><?= $sn ?>.</th> <td><a class="pointer vtr" title="Click to view receipt"><?= $get->ref ?></a></td> <td><?= $get->quantity ?></td> <td>₵<?= number_format($get->totalMoneySpent, 2) ?></td> <td>₵<?= number_format($get->amountTendered, 2) ?></td> <td>₵<?= number_format($get->changeDue, 2) ?></td> <td><?= str_replace("_", " ", $get->modeOfPayment)?></td> <td><?=$get->staffName?></td> <td><?=$get->cust_name?> - <?=$get->cust_phone?> - <?=$get->cust_email?></td> <td><?= date('jS M, Y h:ia', strtotime($get->transDate)) ?></td> <td><?=$get->cancelled? 'Cancelled' : 'Completed'?></td> </tr> <?php $sn++; ?> <?php endforeach; ?>
问题分析
警告核心是视图中尝试访问$get->cancelled属性,但该属性不存在于传递过来的stdClass对象中,常见原因有两种:
- 数据库查询未包含
cancelled字段:控制器/模型查询交易数据时,SELECT语句未选取cancelled字段,导致返回的对象缺少该属性。 - 数据库表无
cancelled字段:交易表本身未定义该字段,无法返回对应数据。
解决方案
方案1:修正数据库查询(根本解决)
找到Search.php对应的数据查询代码(通常是模型方法),确保SELECT语句包含cancelled字段:
// 原错误示例(缺少cancelled) $this->db->select('ref, quantity, totalMoneySpent, amountTendered, changeDue, modeOfPayment, staffName, cust_name, cust_phone, cust_email, transDate'); // 修改后(加入cancelled字段) $this->db->select('ref, quantity, totalMoneySpent, amountTendered, changeDue, modeOfPayment, staffName, cust_name, cust_phone, cust_email, transDate, cancelled');
方案2:视图层容错处理(临时修复)
若暂时无法修改查询逻辑,可在视图中添加属性存在性判断:
// 替换原报错行 <td><?= property_exists($get, 'cancelled') && $get->cancelled ? 'Cancelled' : 'Completed' ?></td> // 或PHP7+可用null合并运算符简化 <td><?= ($get->cancelled ?? false) ? 'Cancelled' : 'Completed' ?></td>
方案3:添加数据库字段(若表中无此字段)
如果交易表本身没有cancelled字段,执行SQL语句添加:
ALTER TABLE transactions ADD COLUMN cancelled TINYINT(1) DEFAULT 0 COMMENT '0=未取消,1=已取消';
内容的提问来源于stack exchange,提问作者Horthman Odame
相关产品推荐
相关产品推荐

