I’m having a problem using MySQLi, I want to create a function to return all users in the database as an Array.
Here the code:
public function getAll() {
$statement = $this->database->prepare('SELECT `id`, `email`, `firstname`, `lastname`, `last_time`, `type`, `activated`, `enabled` FROM `users` ORDER BY `id`');
$statement->execute();
$statement->bind_result($result['id'], $result['email'], $result['firstname'], $result['lastname'], $result['last_time'], $result['type'], $result['activated'], $result['enabled']);
$users = array();
while($statement->fetch()) {
$users[$result['id']] = $result;
}
return $users;
}
The problem is that the &$result has a reference &, so when the $users Array get’s filled up. Every time the while loop gets executed the previous inserted records will be updated to the last values in the &$result variable.
Therefore the overall result $users will have a list of all the same data for each record.
So how can I remove the reference from the &$result variable?
It works by putting each column by it’s own in an new array:
while($statement->fetch()) {
$users[$result['id']] = array($result['id'], $result['email'], ..etc);
}
But that’s too much I guess, there has to be a more simple solution.
Try unsetting it like this: