0

I am fetching data from MYSQL database and Looping through the result but its returning only one row !!! can any one explain what's wrong

 function getAll()
 {
    global $con;

    $SQL  = "SELECT * FROM users";

    $stmt = $con->query($SQL);

    if($stmt->num_rows > 0){

        while($row = $stmt->fetch_row())
        {
            return $row;
        }
    }
 }

2 Answers 2

5

The return should be outside the while loop !

Here is how you can get all the rows :

     function getAll()
     {
        global $con;

        $SQL  = "SELECT * FROM users";

        $stmt = $con->query($SQL);

        if($stmt->num_rows > 0){

            $arr = array();

            while($row = $stmt->fetch_row())
            {
                $arr[] = $row;
            }
            return $arr;
        }
     }

Or you can do something like this return a generator and loop through :

function getAll()
     {
        global $con;

        $SQL  = "SELECT * FROM users";

        $stmt = $con->query($SQL);

        if($stmt->num_rows > 0){


            while($row = $stmt->fetch_row())
            {
                yield $row;
            }
        }
     }

see the result here !

echo '<pre>';

foreach (getAll() as $value) {
 print_r($value);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much that's what i was looking for :)
You are welcome :) accept the answer pls if solved ur problem :)
0

Once you hit a return statement all execution of that function stops. You cannot return multiple times.

You can either return an array of all rows:

function getAll()
{
    global $con;

    $SQL  = "SELECT * FROM users";

    $stmt = $con->query($SQL);

    if($stmt->num_rows > 0) {
        while($row = $stmt->fetch_row())
        {
            $array[] = $row;
        }
        return $array;
    }
 }

Or use it as a generator (probably not what you want):

function getAll()
{
    global $con;

    $SQL  = "SELECT * FROM users";

    $stmt = $con->query($SQL);

    if($stmt->num_rows > 0){

        while($row = $stmt->fetch_row())
        {
            yield $row;
        }
    }
}

2 Comments

i think no need to use loop to get more than one row mysqli_fetch_all one liner for that.
No, this is how its done. There is a way to get all at once, but its just easier to do it this way, especially with a generator.

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.