huge/panique框架中读取game_id属性报错的技术问询
问题解决:带WHERE条件的多数据查询报错处理
问题背景
拥有shows(主键show_id)和games(主键game_id)两张数据表,需要筛选出所有show_id等于指定值的game_id数据,使用huge/panique MVC框架开发,现有代码运行时出现以下警告:
Warning: Attempt to read property "game_id" on int in /home/foxtangocharlie/a.xftc.co/application/view/shows/details.php on line 20
Warning: Attempt to read property "show_id" on int in /home/foxtangocharlie/a.xftc.co/application/view/shows/details.php on line 21
现有代码
控制器代码
public function details($show_id) { $this->View->render('shows/details', array( 'venues' => VenuesModel::getVenue($show_id), 'payment_types' => AdminModel::getPaymentTypes(), 'products' => AdminModel::getAllProducts(), 'games' => ShowsModel::getAllGames($show_id) )); }
模型代码
public static function getAllGames($show_id) { $database = DatabaseFactory::getFactory()->getConnection(); $sql = "SELECT * FROM games WHERE show_id = :show_id" ; $query = $database->prepare($sql); $query->execute(array( ':show_id' => $show_id )); // fetch() is the PDO method that gets a single result return $query->fetch(); }
视图代码(URL:shows/details/$show_id)
<table class="table table-hover"> <thead> <tr> <th scope="col">game_id (primary key)</th> <th scope="col">show_id</th> </tr> </thead> <tbody> <?php foreach ($this->games as $game) { ?> <td><?= $game->game_id; ?></td> <td><?= $game->show_id; ?></td> </tr> <?php } ?> </tbody> </table>
错误原因
模型中使用fetch()方法,该方法仅返回单条查询结果(查询到数据时返回对象,无匹配数据时返回false)。但视图中用foreach循环遍历$this->games,当fetch()返回单条对象时,foreach会将对象的属性值(如int类型的game_id)作为遍历项,导致尝试读取属性时触发“读取int类型属性”的警告。
解决步骤
1. 修改模型方法,获取所有结果
将模型中的fetch()替换为fetchAll(),该方法会返回所有符合条件的结果数组:
public static function getAllGames($show_id) { $database = DatabaseFactory::getFactory()->getConnection(); $sql = "SELECT * FROM games WHERE show_id = :show_id" ; $query = $database->prepare($sql); $query->execute(array( ':show_id' => $show_id )); // fetchAll() returns all matching results as an array of objects return $query->fetchAll(); }
2. 视图修正与空数据判断
修复视图中缺失的<tr>标签,并增加空数据判断避免报错:
<table class="table table-hover"> <thead> <tr> <th scope="col">game_id (primary key)</th> <th scope="col">show_id</th> </tr> </thead> <tbody> <?php if (!empty($this->games)): ?> <?php foreach ($this->games as $game) { ?> <tr> <td><?= $game->game_id; ?></td> <td><?= $game->show_id; ?></td> </tr> <?php } ?> <?php else: ?> <tr> <td colspan="2">暂无相关游戏数据</td> </tr> <?php endif; ?> </tbody> </table>
验证要点
- 确认
fetchAll()返回的是包含多个对象的数组,确保foreach遍历逻辑正常 - 检查数据库中指定
show_id是否存在关联的games数据,验证查询结果正确性
内容的提问来源于stack exchange,提问作者foxtangocharlie
相关产品推荐
相关产品推荐

