我将以下代码作为更大的 Web 应用程序的一部分来搜索员工并返回所需的信息。查询本身几乎不需要时间来完成并返回结果集。似乎需要一些改进的是我目前如何将结果编码到一个数组中,以便 json_encode 返回到前端。我对如何改进代码没有想法(因此我在这里提出问题)。任何想法将不胜感激!
<?php
require_once("class.employee.php");
$employee = new Employee();
$employeeSearch = $employee->searchEmployees($_REQUEST['q']);
$employeeResults = array();
$row_array['id'] = $_REQUEST['q'];
$row_array['empName'] = $_REQUEST['q'];
$row_array['empBusinessTitle'] = '';
$row_array['empFacility'] = '';
array_push($employeeResults, $row_array);
while ($empInfo = $employeeSearch->fetchObject()) {
$row_array['id'] = $empInfo->empUserName;
$row_array['empName'] = ucwords($empInfo->empName);
$row_array['empBusinessTitle'] = $empInfo->empBusinessTitle;
$facilityName = $employee->getFacilityIDByAD($empInfo->empUserName);
$row_array['empFacility'] = isset($facilityName->facilityName) ? $facilityName->facilityName : '';
array_push($employeeResults, $row_array);
}
$ret['results'] = $employeeResults;
echo json_encode($ret);
Class Employee {
public function searchEmployees($query) {
try {
$dbh = new PDO($this->dbDSN, $this->dbUser, $this->dbPass);
$statement = $dbh->prepare("SELECT empID, CONCAT(empFirstName,' ',empLastName) as empName, empUserName, empBusinessTitle from $this->tblEmployeePeople where CONCAT(empfirstname,' ',emplastName) LIKE CONCAT('%',:query,'%') and empUserName != ''");
$statement->bindParam(':query', $query);
$statement->execute();
$dbh = null;
return $statement;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}?>