A4.2 API to Add a Place

Using the following to create an API named add_place.php. See this video for a description of the code below. The PHP program will accept a query string of name value pair arguments for (campus, cuisine, place), then call your stored procedure you created in the previous assignment. Alternatively you can write SQL statements to add a place without using your stored procedure. Your API should return a JSON object containing the error code and accompanying message. Use the same parameter names.

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

$user = '*****';
$pass = '*****';
$host = "localhost";
$database = $user."_CAMPUS";

$campus = 'UHWO';   // Fill in with a campus when testing from the command line
if(isset($_REQUEST['campus'])) $campus=$_REQUEST['campus'];

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

$place = 'Himalayan Kitchen';   // Fill in with a place when testing from the command line
if(isset($_REQUEST['place'])) $place=addslashes($_REQUEST['place']);

if($campus>'' && $place>'') {

    $dsn = "mysql:host=$host;dbname=$database";
    $pdo = new PDO($dsn, $user, $pass);
    
    $sql = "CALL ADD_PLACE(:campus,:cuisine,:place, @err, @msg);";

    $statement = $pdo->prepare($sql);
    $statement->bindValue("campus", $campus);
    $statement->bindValue("cuisine", $cuisine);
    $statement->bindValue("place", $place);
    $statement->execute();
    
    $sql = "SELECT @err AS err, @msg AS msg2";

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

    if ($rec = $statement->fetch()) {
        $err = $rec['err'];
        $msg = $rec['msg2'];
    }
}else{
    $err = "1";
    $msg = "campus or place not specified";
}

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

To test your API you can use the same tests you used to test your ADD_PLACE routine. First you may have to delete Himalayan Kitchen as the favorite Nepalese at UHWO if it is still present in your database.