Search code examples
phpwhile-loopreturn

return value from while loop in php


hi I'm a kind of a newbie to the MVC in programming. I tried to findout the solution from stackoverflow and other sites by googling but none of are worked for me.

Please guide me where i'm doing mistake.

My controller code:

function getAllusers($id){
    global $conn;
    $users = [];
    $sql = "SELECT * from Users WHERE id=$id";
    $ownerdata = mysqli_query($conn, $sql);
    while($row = mysqli_fetch_assoc($ownerdata))
    {
        $users[] = $row;
    }
    return $users;
}

View (piece of) code:

    getAllusers($user_id);
    var_dump($users);

In var_dump($users); I'm getting null and in controller if I do var_dump() before return I'm getting an array.

Please, guide me to overcome this. Thank you!


Solution

  • Your function getAllusers() returns the value so, you need to put this value into a variable to use inside your view.

    You have two files:

    Controller: That communicates with your data (database, etc.) View: Where you display your data that you collected from some controller call.

    You can see more on MVC patterns in how you organize a structure to create systems.

    What happens when you created a function getAllusers()? The function get the data on database and create the array as showed on your question.

    When you call the function getAllusers() your $users variable are on the scope of function. This means that $users variable are acessible only inside the function getAllusers(). See more details here.

    As you call getAllusers() in another file, when the function ends, the $users inside function are erased from memory. So, the return function is to get the piece of data that you need and get back.

    So, when you create a new variable with the same name outside the function like showed on the code below, this new variable simply receives the return from the function called and you don't lose the result of your work.

    You also can do the same thing with other variable name when you receive the value.

    Try this:

       $users = getAllusers($user_id);
    

    This will put the return from getAllusers() function on variable $users.