How to Query with Input Data

Web services can accept input from a GET or a POST. For the purposes here, you use a GET request to accept a URL for your site status web service.

This listing shows the new site status web service, with code added to retrieve the URL from the query string.

<?php
$header = "Content-Type: application/json";
header($header);
 
if (isset($_GET['siteURL'])) {
    $site = $_GET['siteURL'];
} else {
    print json_encode(array("siteStatus" => "No site specified"));
    exit;
}
 
$dbLink = mysqli_connect('localhost','USER','PASSWORD','sites');
 
if (!$dbLink) {
    $row = array("siteStatus" => "Database Error");
    print json_encode($row);
} else {
$escSite = mysqli_real_escape_string($dbLink,$site);
 
    $query = "SELECT siteStatus FROM siteStatus WHERE siteURL = '{$escSite}'";
    if ($result = mysqli_query($dbLink,$query)) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        if (is_null($row)) {
            $row = array("siteStatus" => "Error - Site Not Found");
        }
    } else {
        $row = array("siteStatus" => "General Error");
    }
    print json_encode($row);
    mysqli_close($dbLink);
} // End else condition (for database connection)
 
?>
The primary code addition for this new web services is at the top:
if (isset($_GET['siteURL'])) {
    $site = $_GET['siteURL'];
} else {
    print json_encode(array("siteStatus" => "No site specified"));
    exit;
 }

This code checks to see if the siteURL variable is on the query string and if it is, sets it to the $site variable.

Later in the code, the $site variable is escaped so that it's safe to use in a query, and the query itself is changed to use that newly escaped variable:

$escSite = mysqli_real_escape_string($dbLink,$site);
$query = "SELECT siteStatus FROM siteStatus WHERE siteURL = '{$escSite}'";

With that code in place, the web service can be called again. This time, though, instead of just loading the web service like http://localhost/sitestatus.php, you need to include the URL to check as part of the address, like so:

http://localhost/sitestatus.php?siteURL=http%3A%2F%2Fwww.braingia.org

But wait! What's all that %3A%2F%2F in the http://www.braingia.org URL? Those are URL-encoded characters. Certain characters are reserved or restricted from use in a URL. It just so happens that :// are some of those restricted characters. Therefore, they need to be converted (or escaped) to be a safe URL to use.

In any event, when that URL is loaded, the site is looked up in the database and its status is returned.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com