skip to Main Content

I have a web service that queries a database for a region and then returns the results in JSON format. It works but it is not displaying things like “400 bad request” when a bad request is made. The page just displays;

[]

Why is this? I thought apache had built in HTTP error code handling. What I want the script to do is when a bad request is made or a 404 error is occured, to return the specific code.

Here is my php script;

<?php

$a = $_GET["region"];
$conn = new PDO ("mysql:host=localhost;dbname=***;", "***", 
"***");

$results = $conn->query("SELECT * FROM pointsofinterest WHERE region='$a'");
$resultsAsAssocArray = $results->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($resultsAsAssocArray);

?>

2

Answers


  1. As far as I can understand from your code, a bad request is not being made.

    You’re echoing $resultsAsAssocArray which simply just contains your SELECT result. Which in this case happens to be empty, is my guess.

    Try running the same SQL query from your command line or via PHPMyAdmin and see if you get any results returned.

    EDIT: If you wish to return a 404 error code when no result is returned then you should make use of the http_response_code() function.

    An example is illustrated here: https://stackoverflow.com/a/41593478/1308765

    Login or Signup to reply.
  2. PHP can automatically set a status of 500 in case of an error (if display_errors is disabled) but for anything else, you need to explicitly tell it how to respond.

    For example, say you want to respond with a 404 if there are no records found…

    $conn = new PDO ('mysql:host=localhost;dbname=***;charset=utf8', '***', '***', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    
    // Note that I'm using a prepared statement
    $stmt = $conn->prepare('SELECT * FROM pointsofinterest WHERE region = ?');
    
    $stmt->execute([filter_input(INPUT_GET, 'region')]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($results) === 0) {
        http_response_code(404);
    }
    
    echo json_encode($results);
    

    See http://php.net/manual/function.http-response-code.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search