A4.1 API to Search Places

Write an API named search_places.php that returns an array of (campus, place, cuisine) records in a JSON object. The API accepts an optional query string of name-value pairs as arguments for campus, cuisine, and place. The arguments are used to construct the WHERE clause of CAMPUS_PLACES NATURAL JOIN PLACE_CUISINES. Specifying any of the arguments narrows the search to records equal to the argument or arguments.

For example,

  • (a) search_places.php?campus=UHM will return UHM’s favorite places and cuisines.
  • (b) search_places.php?cuisine=Burgers will return all the favorite Burger places for each campus.
  • (c) search_places.php?place=Himalayan Kitchen will return any campuses that lists this place as a favorite.
  • (d) search_places.php?campus=UHM&cuisine=Italian will return UHM’s favorite Italian place.
  • (e) search_places.php (without any arguments) will return all the favorite places for all the campuses.

Note that the array returned each time contains (campus, cuisine, place) triples.

This program can start with the following PHP code: See this video for the first part, then this video for the rest of this PHP version.

<?php
// search_places.php
header('Content-Type: application/json');

$user = '*****';  // username you use to log into cPanel
$pass = '*****';  // password you use to log into cPanel
$host = "localhost";
$database = $user."_CAMPUS";

$campus = '';
if(isset($_REQUEST['campus'])) $campus=$_REQUEST['campus'];

$cuisine = '';
if(isset($_REQUEST['cuisine'])) $cuisine=$_REQUEST['cuisine'];

$place = '';
if(isset($_REQUEST['place'])) $place=addslashes($_REQUEST['place']);

$dsn = "mysql:host=$host;dbname=$database";
$pdo = new PDO($dsn, $user, $pass);

$sql = "SELECT CAMPUS, PLACE, CUISINE FROM CAMPUS_PLACES NATURAL JOIN PLACE_CUISINES";

/* add your code to add WHERE clause to SQL statement */

$places = Array();
$statement = $pdo->query($sql);

while ($row = $statement->fetch()) array_push($places,$row);

$out= json_encode([
        "msg" => "$sql",
        "error" => "$err",
        "campus" => "$campus",
        "cuisine" => "$cuisine",
        "place" => "$place",
        "places" => $places
    ]);
    
echo $out;
?>