how do we use mysqli properly to fetch all the rec

2019-08-13 03:40发布

问题:

I am getting only one row, can someone please tell me how to get all the data from the table column of my database table ?

   public function getCategories(){
    $result = $this->db->query('SELECT * FROM newscat');
    $rows = array();
        while($row = $result->fetch_assoc()){
               $rows[] = $row;
               return $rows;
           }
     }

回答1:

You're returning from within the loop. That will break it in the first round.

return outside the loop.



回答2:

do the minor change

public function getCategories(){
    $result = $this->db->query('SELECT * FROM newscat');
    $rows = array();
    while($row = $result->fetch_assoc()){
             $rows[] = $row;
    }
    return $rows;
 }


回答3:

Your problem is the return $rows;. It should reside after the while. The thing is that it will enter the while, put the first row in the array, and then immediately return it. What you want is to let the while do its thing, and after the it finished, return the array.



回答4:

If you are using mysqli. Then you can use its apiFfetch_all to get all the rows at once.

For example : $array=$result->fetch_all(MYSQLI_ASSOC);

The above code will get all associated rows in the corresponding array.



标签: php mysql mysqli