Reputation: 13
I am relatively new to PHP and I am having difficulty with getting the correct output from a class. I am using SELECT * in a prepared statement in an attemp to pull back a row WHERE login status is set to in. Thge code I have at present creates an array, but if more than one user is logged in, the second result appears to be written over the first, only allowing me to display one row.
Normally I would achieve such a task with a 2d array, where each row is an array containing an array of key-value pairs, but I am having difficulty getting this to work.
The method is as follows:
public function getUserByLoginStatus($loginStatus) {
$session=new mysqli(self::SERVERNAME,self::USERNAME,self::DBPASS);
mysqli_select_db($session,"users");
$statement=$session->prepare("SELECT * FROM `logins` WHERE `loginstatus`= ? ;");
$statement->bind_param('s', $this->loginStatus);
$statement->execute();
$statement->store_result();
$statement->bind_result($userId,$userHandle,$eMail,$password,$gender,
$loginStatus,$currentSess,$currentIpv4,$currentIpv6,
$lastActivity,$lastLoginDate,$lastLoginTime);
$numberOfRows=$statement->num_rows;
if($numberOfRows < 1)
{
$errorMessage="No users currently online";
$statement->close();
$session->close();
return $errorMessage;
}
else
{
while($statement->fetch())
{
$returnArr=['userid' => $userId, 'userhandle' => $userHandle, 'email' => $eMail,
'password' => $password, 'gender' => $gender, 'loginstatus' => $loginStatus,
'currentsess' => $currentSess, 'currentipv4' => $currentIpv4, 'currentipv6' => $currentIpv6,
'lastactivity' => $lastActivity, 'lastlogindate' => $lastLoginDate, 'lastlogintime' => $lastLoginTime];
}
$statement->close();
$session->close();
return $returnArr;
}
}
If the table col is set to 'out' or 'deactivated', the correct error message is displayed. If any 1 user is set to 'in' I can view data from the fields. If >1 user is online, only the last user displays (overwritten I believe).
Here is how I am trying to print this out at present:
Creating an instance, attempting to output data.
Upvotes: 1
Views: 413
Reputation: 2135
Try following while loop
while($statement->fetch())
{
$returnArr[]=['userid' => $userId, 'userhandle' => $userHandle, 'email' => $eMail, 'password' => $password, 'gender' => $gender, 'loginstatus' => $loginStatus, 'currentsess' => $currentSess, 'currentipv4' => $currentIpv4, 'currentipv6' => $currentIpv6, 'lastactivity' => $lastActivity, 'lastlogindate' => $lastLoginDate, 'lastlogintime' => $lastLoginTime];
}
Upvotes: 1