Copy link to clipboard
Copied
Hi,
I have an html page that send out a jQuery post to a php PDO page to query the db with a select statement. The result gets sent back to the HTML page as json_encode....
The result may return an empty result with no records.
I can check for this using count...
if (count($records) > 0) {
$output = [];
foreach ($records as $key=>$record) {
$output[$key]["First"] = $record['First'];
$output[$key]["Last"] = $record['Last'];
//etc.
}else{
$output = [];
//????? How do I create a proper $output[$??] ??? response to send back a failed - empty result to the HTML PAGE?
}
print_r (json_encode($output));
Thanks in advance - Dave
Copy link to clipboard
Copied
In your else block:
$output = 'No results found';
In your jQuery, check whether the response == 'No results found'. If it is, display that. Otherwise, process the results as normal.
Copy link to clipboard
Copied
Is there a reason you're using print_r? If you want to inspect it yourself you can use a JSON prettyify formatter argument like (PHP 5.4+): json_encode( $output, JSON_PRETTY_PRINT ). Using print_r is going to invalidate the JSON to any API, but I suspect you're just investigating the results yourself. Consider grabbing one of the many JSON extensions for browsers that automatically allows you to receive and view JSON data in a pretty way instead and work directly with the JSON.
That aside, I always like to send a status on any API endpoints that return data with a predefined set of messages I'll understand on the other end. Every JSON object I send back has a "status" (int), "message" (helpful human info) and/or the "results". That way I'm comparing against a bunch of useful possible "status" that will let me debug the client side much easier.
e.g. Success (code 1):
{
"status": "1",
"message": "success",
"results": [
{
"First": "John",
"Last": "Doe",
...
},
...
]
}
I tend to make the status codes constants defined in a global config or modular to the part of the app I'm making, depends on the situation. Either a class for constants or just defining them with regular variables like $_ERROR_NO_RESULTS = -1; so, e.g.:
// response codes
$_ERROR_NO_RESULTS = -1;
// (or bundle)
$_ERROR_NO_RESULTS (object) array( 'status' => -1, 'message' => "error: no results" ) ;
// then later (bundle is easiest)
$response = $_ERROR_NO_RESULTS;
echo json_encode( $response, JSON_PRETTY_PRINT );
No results isn't always an error but if you were expecting some then it just may be.
Over time and as any application grows it should be a centralized thing but making a status has helped me assign a ton of useful errors so I rarely need to look at the PHP, the codes let me know exactly what's going on for each response. Much easier to test against as well.