使用prepare语句我只获取一行,我试着循环所有行,但只有一行女巫被提取。请帮助我如何获取数据库中的所有行而不是一行
PHP函数: .....
public function StudentsOfParent($mobile){
$stmt = $this->conn->prepare("SELECT
a.id,
a.name,
a.mobile,
c.id as sutdentId,
c.user_id,
c.full_name,
c.school,
c.level,
c.year,
c.id
from users a
join students c
on a.id = c.user_id where a.mobile= ?");
$stmt->bind_param("i", $mobile);
if ($stmt->execute()) {
while ($user = $stmt->get_result()->fetch_assoc())
{
$stmt->close();
// return user's results
return $user;
}
}
else {
return NULL;
}
}
.....
用于访问上述功能的外部php文件:retrieve.php:
<?php
include './DbHandler.php';
$db = new DbHandler();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['mobile'])){
$mobile = $_POST['mobile'];
$user = $db->StudentsOfParent($mobile);
if ($user != false) {
// user found successfully
$response["error"] = FALSE;
$response["user"]["id"] = $user["id"];
$response["user"]["sutdentId"] = $user["sutdentId"];
$response["user"]["user_id"] = $user["user_id"];
$response["user"]["full_name"] = $user["full_name"];
$response["user"]["school"] = $user["school"];
$response["user"]["level"] = $user["level"];
$response["user"]["year"] = $user["year"];
// $response["user"]["photo"] = $user["photo"];
echo json_encode($response);
// $json = json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Sorry we could not find you !";
echo json_encode($response);
}
}
else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
答案 0 :(得分:0)
使用prepare语句我只获取一行,我试着循环所有行,但只有一行是女性被提取。
那是因为你在$user
循环本身的第一次迭代中返回while
,循环甚至不会继续进行第二次迭代。另外,您还在第一次迭代中关闭语句对象$stmt->close();
。相反,您的代码块应该是这样的:
// your code
if ($stmt->execute()) {
$result = $stmt->get_result();
$usersArr = array();
while ($user = $result->fetch_assoc()){
$usersArr[] = $user;
}
$stmt->close();
return $usersArr;
} else {
return NULL;
}
// your code
现在返回的$usersArr
数组是一个多维数组,您需要适当地循环以获取所有用户的详细信息。如果要查看完整的数组结构,请执行var_dump($usersArr);
。