我正在制作一个应用程序,它会在列表视图中按特定商店列出员工。我在DB_Functions.php文件中的当前函数是:
public function getEmployeeList($name) {
$stmt = $this->con->prepare("SELECT employee_name FROM employees WHERE name = ?");
$stmt->bind_param('s', $name);
if ($stmt->execute()) {
$employee_list = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (empty($employee_list)) {
return NULL;
} else {
return $employee_list;
}
}
}
在我的employees.php文件中,我有以下代码:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array('error' => FALSE);
if (isset($_POST['name'])) {
$name = $_POST['name'];
$employee_list = $db->getEmployeeList($name);
if ($employee_list != false) {
$response['error'] = FALSE;
//EMPLOYEE LIST OBJECT HERE
} else {
$response['error'] = TRUE;
$response['error_msg'] = 'No employees have been added to this profile.';
echo json_encode($response);
}
} else {
$response['error'] = TRUE;
$response['error_msg'] = 'You have not logged in to your store\'s account, please log in first.';
echo json_encode($response);
}
?>
我想在上面的注释空格中有一个employee_list对象。类似的东西:
$response['employee_list']['0'] = $employee_list['0'];
$response['employee_list']['1'] = $employee_list['1'];
$response['employee_list']['2'] = $employee_list['2'];
等等...等等......
之后,JSONObject返回到Android应用程序,内容将列在listview中。我需要一个for循环(我认为),因为员工编号永远不会被知道,因为每个商店都可以按照自己的意愿添加和删除员工。有人可以指出我正确的方向,并建议我是否使用正确的方法,其余的代码。感谢。
答案 0 :(得分:3)
首先,在DB_Functions.php中,您应该返回mysqli_result对象。 因此你的DB_Functions应该是这样的:
public function getEmployeeList($name) {
$stmt = $this->con->prepare("SELECT employee_name FROM employees WHERE name = ?");
$stmt->bind_param('s', $name);
if ($stmt->execute()) {
// we get the mysqli_result object without calling the fetch_assoc() on it
$result = $stmt->get_result();
$stmt->close();
// if the count is less than 1, no result found, hence return null
if ($result->num_rows < 1) {
return null;
} else {
// we return the mysqli_result object without calling the fetch_assoc() on it
return $result;
}
}
}
在您的employees.php中,您想要的是这样的:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array('error' => FALSE);
if (isset($_POST['name'])) {
$name = $_POST['name'];
$result = $db->getEmployeeList($name);
// do an early check for if result returns null or is not set
if (is_null($result) || !$result) {
$response['error'] = TRUE;
$response['error_msg'] = 'No employees have been added to this profile.';
} else {
$response['error'] = FALSE;
//EMPLOYEE LIST OBJECT HERE
// since $result->fetch_assoc() returns one row at a time, you want to loop through each row and get the appropriate data
while ($row = $result->fetch_assoc()) {
// inject the current into the employee_list array
$response['employee_list'][] = $row;
}
}
} else {
$response['error'] = TRUE;
$response['error_msg'] = 'You have not logged in to your store\'s account, please log in first.';
}
// echo response gets called no matter what
echo json_encode($response);
希望有所帮助