Reputation: 59511
I'm trying to fetch the result of a query to my database. I have no problems doing so when the resultset is just 1 row, but when it's multiple rows I only get the first one.
Here is my db:
-----keys-------------------
| id | key_nbr | date |
----------------------------
| 42 | abc123 | xxxx |
| 49 | 789xyz | wxyz |
----------------------------
My function:
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
$row = $stmt->fetch_array(MYSQLI_ASSOC);
return $row;
}
}
return null;
}
Output when doing print_r($row);
is only the first row:
Array ( [id] => 42 [key_nbr] => abc123 [date] => xxxx)
How to make it print all rows?
Upvotes: 0
Views: 85
Reputation: 3078
You have to check for total number of rows before fetching the data, if it's not zero then execute the loop and fetch all records.
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
if($stmt->num_rows != 0) {
$row = array();
while($r = $stmt->fetch_array(MYSQLI_ASSOC)) {
$row[] = $r;
}
return $row;
}
}
}
return null;
}
Upvotes: 2