Reinis Krūkliņš
Reinis Krūkliņš

Reputation: 19

How to access an object inside an array

I have this small code:

$user = Database::getInstance()->query("SELECT username FROM users");
if ($user->count()) {
    foreach ($user as $users) {
        echo $users->username;
    }
}
var_dump($users);die();

This gives me an error:

Notice: Trying to get property 'username' of non-object in C:\xampp\htdocs\finaltask\test.php on line 8
array(2) { [0]=> object(stdClass)#5 (1) { ["username"]=> string(10) "reinisk157" } [1]=> object(stdClass)#6 (1) { ["username"]=> string(9) "reinisk22" } }

If I understand correctly, Im trying to retrieve an object from an array, but I have no idea how else to get this data out of my DB. Please let me know if you need more details.

Upvotes: 0

Views: 83

Answers (4)

Reinis Krūkliņš
Reinis Krūkliņš

Reputation: 19

thamks for all the answers, i'll try them as well. The one I made it work was:

echo $users[0]->username;

Upvotes: 0

MNN
MNN

Reputation: 302

First, semantically, with that query you fetch users, not just one user. It's not important when it comes to the code itself, but it's important to understand it :)

$users = Database::getInstance()->query("SELECT username FROM users");
// I prefer is_null over count(), when a query returns 0 rows turns on null
if (!is_null($users)) {
    foreach($users as $user){
        //Try calling it this way
        echo $user['username'];
    }
}

Upvotes: 0

Satish Saini
Satish Saini

Reputation: 2968

Use $usersResult = $users->fetchAll(PDO::FETCH_OBJ); and then foreach as you used.

$users = Database::getInstance()->query("SELECT username FROM users");
$usersResult = $users->fetchAll(PDO::FETCH_OBJ);
if ($usersResult->count()) {
    foreach ($usersResult as $user) {
        echo $user->username;
    }
}
var_dump($usersResult);
die();

Note: I have changed $users to $user while parsing data in the loop because this makes more sense for individual user's data.

Hope this works!

Upvotes: 1

DarkMukke
DarkMukke

Reputation: 2489

There are some issue of scope and naming here that may confuse you.

Scope of a foreach

foreach($list as $item) {
    // ... do something
}
echo $item;

When looping through a list/array, the last item of the loop will still be available after the loop. That's why the dump looks like it does, as you are dumping the wrong thing.

$userResult = Database::getInstance()->query("SELECT username FROM users");
if ($userResult->count()) {
    foreach ($userResult as $user) {
        echo $user->username;
    }
}
var_dump($userResult);die();

Upvotes: 1

Related Questions