I have the following code as part of a larger web application to search for employees and return the required information. The queries themselves take little to no time to complete and return the result set. What appears to need some improvement is how I am currently encoding the results into an array for json_encode to return to the front end. I am out of ideas for how to improve upon the code (hence my question here). Any ideas would be greatly appreciated!
<?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();
}
}
}?>
The functions called in the where clause breaks any index you might have on these fields. Here is the worst part of your query from a performance standpoint.
First, why the need for the second CONCAT? Just do this
However, would still hit the index breaking penalty for the first Concat function. Also, why the wildcard Likes? You probably want an exact equality check.
I would break the passed in request value ‘q’ down into 2 parts a first and last name, and pass that to the search function.
Try this in the search function:
Then change your query to be:
Then add the binding with wildcard like this: