Skip to content

Commit

Permalink
Add an API method to search business names
Browse files Browse the repository at this point in the history
Toward #85.
  • Loading branch information
waldoj committed Sep 21, 2019
1 parent dcf4c93 commit 7e54179
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/.htaccess
Original file line number Diff line number Diff line change
Expand Up @@ -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"
38 changes: 38 additions & 0 deletions api/search.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/autoloader.php';

/*
* Use the search string passed in the URL
*/
if ( isset($_GET['query']) )
{
$query = filter_var($_GET['query'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
}

$database = new Database;
$db = $database->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);
32 changes: 32 additions & 0 deletions includes/class.Business.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

}

}

0 comments on commit 7e54179

Please sign in to comment.