return value from while loop in php
Get the solution ↓↓↓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);
Invar_dump($users);
I'm gettingnull
and in controller if I dovar_dump()
before return I'm getting an array.
Please, guide me to overcome this. Thank you!
Answer
Solution:
Your functiongetAllusers()
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 functiongetAllusers()
? The function get the data on database and create the array as showed on your question.
When you call the functiongetAllusers()
your$users
variable are on the scope of function. This means that$users
variable are acessible only inside the functiongetAllusers()
. See more details here.
As you callgetAllusers()
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 fromgetAllusers()
function on variable$users
.
Answer
Solution:
Just one tiny thing:
$users = getAllusers($user_id);
var_dump($users);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.