Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get array of objects from query result

Simplified version of the problem:

So I have this query which is inside a function.

$query = "SELECT * FROM users";
$result = mysql_query($query);

How I want to use mysql_fetch_object() to get an object from a row.

Because in the end I wanted to get an array of objects I do this:

while ($a[] = mysql_fetch_object($result)) { // empty here }

In the end the function just returns $a. And it works almost fine.

My problem is that mysql_fetch_object will return at the end a NULL "row" (which is normal because the result ended but I still assigned it to the array).

Any ideas on how to do this in a decent way? Thanks in advance.

like image 835
Valentin Despa Avatar asked Aug 14 '26 12:08

Valentin Despa


2 Answers

Or you could move the assignment from the while condition to the while body like:

<?php
while ($entry = mysql_fetch_object($result)) {
   $a[] = $entry;
}
like image 179
Yoshi Avatar answered Aug 17 '26 01:08

Yoshi


mysql_fetch_object actually returns FALSE if there are no more rows. I would do this:

$a = array();
while (($row = mysql_fetch_object($result)) !== FALSE) {
  $a[] = $row;
}
like image 35
John Hargrove Avatar answered Aug 17 '26 02:08

John Hargrove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!