I am working on converting a procedural php code to mysqli OOP the code below returns all users based on joined information
public static function find_all_users()
{
$db = getConn();
$stmt = $db->prepare("
SELECT *
FROM users
JOIN roles
WHERE roles.role_id = users.role_id
ORDER BY created_at");
$stmt->execute();
$user = $stmt->get_result();
$stmt->close();
return $user->fetch_object();
}
When I do a var_dump it gives me and object, however on the page to display it i call
$users = User::find_all_users();
Then
<?php if (!empty($users)) : ?>
<ul>
<?php foreach ($users as $user) : ?>
<li>
<div>
<h2><?= $user['name'] ?></a></h2>
<p><?= $user['email'] ?></p>
</div>
</li>
<?php endforeach; ?>
</ul>
<?php else : ?>
<p>No User found.</p>
<?php endif; ?>
If i try to use $this->id or $user->id it tells me I am trying to get a non object but when I var_dump $users it returns a object?
object(stdClass)[5]
public 'id' => int 1
public 'name' => string 'bigjah' (length=4)
public 'email' => string '[email protected]' (length=22)
public 'password' => string '$2y$10$TOPc3JHjtoxfJQI14EMRj.ybVkgEPo4KB6.yB5s6pK/PHWO1GOaDy' (length=60)
public 'created_at' => string '2021-09-25 01:32:38' (length=19)
public 'about' => null
public 'ip_address' => string '127.0.0.1' (length=9)
public 'reset_token' => null
public 'reset_key' => null
public 'confirmed' => string '857795025069' (length=12)
public 'verified' => int 0
public 'role_id' => int 4
public 'role_title' => string 'Administrator' (length=13)
CodePudding user response:
Probably what you want is ->fetch_fields();
on your model like following
return $user->fetch_fields();
CodePudding user response:
You are iterating over a single object, if that dump is the result of dumping $usrs. Therefore, change the way you fetch the statement into $st->fetchAll(PDO::FETCH_CLASS);
if you are using PDO. But I see that you are not so $user -> fetch_all(MYSQLI_ASSOC);
To use the result of your query as an object
while ($user = find_all_users()): ?>
<h2><?= $user->name ?></a></h2>
}
That means you loop every time you get an instance of the object from your current function.