当前位置: 动力学知识库 > 问答 > 编程问答 >

mysqli - PHP return msqli_fetch_assoc from a function

问题描述:

I have a function in PHP that executes a query and returns the resutls:

public function findUsersByParentId ( $parentId ) {

$query = " SELECT * FROM users u WHERE u.parent_id = " .$parentId ;

$con = DBHelper::getDatabaseConnection();

$queryResult = mysqli_query($con,$query);

$results = mysqli_fetch_array($queryResult,MYSQLI_ASSOC);

mysqli_close($con);

return $results;

}

and then I want to loop through the results in another file:

....

$values = $UserModel->findUsersByParentId ( $parentId );

foreach ( $values as $row ) {

echo $row['id'] . " : " . $row['name'];

}

but it does not work. If if use the print-loop inside the first function if prints Ok. If I use the print-loop with the "return"ed results it does not work. Any suggestions?

网友答案:

$results = mysqli_fetch_array($queryResult,MYSQLI_ASSOC); will only get one row at a time.

so you have to do something like:

while($row=mysqli_fetch_array($queryResult,MYSQLI_ASSOC)){
   $results[]=$row;
   }
return $results;
分享给朋友:
您可能感兴趣的文章:
随机阅读: