0

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?

2
  • $row = $stmt->fetch_all(MYSQLI_ASSOC); instead of $row = $stmt->fetch_array(MYSQLI_ASSOC); Commented Sep 12, 2014 at 16:21
  • 1
    Sidenote: keys is a MySQL reserved keyword. Wrap it in backticks ` or use another name for it. Having used error reporting which you're most probably not doing, would have signaled the error. Always use error reporting. Commented Sep 12, 2014 at 16:32

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.