2

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.

asked May 30, 2011 at 7:42

4 Answers 4

8

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

<?php
while ($entry = mysql_fetch_object($result)) {
 $a[] = $entry;
}
answered May 30, 2011 at 7:45
Sign up to request clarification or add additional context in comments.

Comments

3

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;
}
answered May 30, 2011 at 7:48

1 Comment

I've always considered the type checking good practice when dealing with boolean return values in PHP. In this case it won't matter, but it numerous others, it most certainly does. It's a defensive programming practice, IMO.
0

You can just add

array_pop($a);

after the while

http://php.net/manual/en/function.array-pop.php

answered May 30, 2011 at 7:44

1 Comment

Not generally advised, but since this will always be there because that is the exit condition on the loop, this is a reasonable solution. I'd add a comment explaining why you are array_poping though.
0

This question seems like duplicate of how to fetch all the row of the result in php mysql?

//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $this->sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);
answered Oct 5, 2017 at 21:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.