From 7e5417978a4e8133d3c861f2e95ae0e4adba0c7d Mon Sep 17 00:00:00 2001 From: Waldo Jaquith Date: Sat, 21 Sep 2019 14:07:39 -0400 Subject: [PATCH] Add an API method to search business names Toward #85. --- api/.htaccess | 1 + api/search.php | 38 +++++++++++++++++++++++++++++++++++++ includes/class.Business.php | 32 +++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 api/search.php diff --git a/api/.htaccess b/api/.htaccess index 8c4603e..930935c 100644 --- a/api/.htaccess +++ b/api/.htaccess @@ -6,6 +6,7 @@ Header add Access-Control-Allow-Origin "*" RewriteEngine On RewriteRule ^business/(.+)$ business.php?id=$1 [QSA] +RewriteRule ^search/(.+)$ search.php?query=$1 [QSA] # By default, API data expires in a week Header set Cache-Control "max-age=604800, public" diff --git a/api/search.php b/api/search.php new file mode 100644 index 0000000..5eb54de --- /dev/null +++ b/api/search.php @@ -0,0 +1,38 @@ +connect(); + +if (!$db) +{ + header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error", true, 500); + echo json_encode('Error'); + exit; +} + +/* + * Get the first 50 matching records + */ +$business = new Business; +$business->db = $db; +$business->query = $query; +$results = $business->search(); + +if (!is_array($results)) +{ + header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); + echo json_encode('Error'); + exit; +} + +echo json_encode($results); diff --git a/includes/class.Business.php b/includes/class.Business.php index 4ee5d89..387845d 100644 --- a/includes/class.Business.php +++ b/includes/class.Business.php @@ -32,4 +32,36 @@ function fetch() } + /* + * Search matching business records, return the first 100 + */ + function search() + { + + if (!isset($this->db) || !isset($this->query)) + { + return FALSE; + } + + $sql = 'SELECT * + FROM corp + WHERE Name LIKE "%' . $this->query . '%" + LIMIT 100'; + $result = $this->db->query($sql); + + if ($result->numColumns() == 0) + { + return false; + } + + $this->results = []; + while ($business = $result->fetchArray(SQLITE3_ASSOC)) + { + $this->results[] = $business; + } + + return $this->results; + + } + }