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

如何访问数组中的对象?PHP数据库查询代码报错求助

Fixing "Trying to get property 'username' of non-object" Error

Hey there! Let's break down what's going on with your code and fix that frustrating error.

What's Causing the Issue?

From your var_dump($users) output, I can see your database query is returning an array of stdClass objects (each with a username property). The error pops up because somewhere in your loop, you're trying to access the username property on something that isn't an object—most likely due to confusing variable names or how your custom Database class returns results.

Looking at your code, using $user for the full result set and $users for individual loop items creates unnecessary confusion. It's also possible your Database class's query() method returns a result set that behaves unexpectedly when you iterate over it directly.

Solutions to Fix the Code

1. Clean Up Variable Names & Add Safety Checks

Let's rename variables to eliminate confusion, plus add checks to ensure we only access properties on valid objects:

// Rename to $userList for clarity—this holds all your query results
$userList = Database::getInstance()->query("SELECT username FROM users");

// Check if we have results: use count() if $userList is an array, or ->count() if it's a result object
if (count($userList)) {
    // Use $singleUser for individual items in the loop
    foreach ($userList as $singleUser) {
        // Add a safety check to confirm we're dealing with a valid object
        if (is_object($singleUser) && property_exists($singleUser, 'username')) {
            echo $singleUser->username;
        }
    }
}

var_dump($userList);

2. Explicitly Fetch Objects from the Result Set

If your Database class uses PDO under the hood (a common setup), you might need to explicitly fetch results as objects instead of relying on implicit iteration. Try this approach:

$stmt = Database::getInstance()->query("SELECT username FROM users");
// Fetch all results as stdClass objects
$userList = $stmt->fetchAll(PDO::FETCH_OBJ);

if (count($userList)) {
    foreach ($userList as $singleUser) {
        echo $singleUser->username;
    }
}

var_dump($userList);

Key Takeaways

  • Avoid overlapping variable names (like $user and $users)—it makes debugging harder and can lead to accidental variable overwrites.
  • Always add safety checks (like is_object()) when accessing object properties, especially with database results that might not always return your expected format.
  • If you're using a custom database class, double-check its documentation to confirm how query() returns results (is it an array, a result set object, or something else?).

内容的提问来源于stack exchange,提问作者Reinis Krūkliņš

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:29:55