springthorpeSoftware
asked on
How to gracefully handle MySQL errors in a JSON request?
New to AJax/JSON and need assistance in handling MySQL errors on the called PHP page.
All of the examples I've found online do a "die" if the query fails or no records are returned. I want to gracefully handle errors by showing an alert if the call fails. (This is also a huge advantage to me in debugging.) The text I want to show is generated on the PHP page.
Rough code follows.
Thanks!
Bruce
javascript function code:
All of the examples I've found online do a "die" if the query fails or no records are returned. I want to gracefully handle errors by showing an alert if the call fails. (This is also a huge advantage to me in debugging.) The text I want to show is generated on the PHP page.
Rough code follows.
Thanks!
Bruce
javascript function code:
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
txt = xmlhttp.responseText;
var R = JSON.parse(txt);
// load variables, display info, etc.
}
xmlhttp.open("GET","ajax_user_data.php?id=" + rqstr, true);
xmlhttp.send();
PHP page code:
<?php
header("content-type:application/json");
session_start();
include_once("adiInclude.php");
$id = $_GET['id'];
$txt = '';
$connAJAX = ConnectDB(); // function is in include file
$sql = 'SELECT * FROM users WHERE user_id = ' . $id;
$qry = mysql_query($sql, $connAJAX);
if (!$qry) {
$txt = 'JSON Users query failed: ' . mysql_error($connAJAX) . " SQL: " . $sql;
} elseif (mysql_numrows($qry) == 0) {
$txt = "JSON Invalid User ID: " . $id;
mysql_free_result($qry);
} else {
$row = mysql_fetch_assoc($qry);
foreach($row as $i => $v) {
if ($i == "user_id" || $i == "user_cam" || $i == "user_country" || $ == "user_via") {
$txt .= ', "' . $i . '":' . $v . '';
} else {
$txt .= ', "' . $i . '":"' . $v . '"';
}
}
$txt = '{ ' . substr($txt, 2) . ' }';
mysql_free_result($qry);
}
mysql_close($connAJAX);
echo $txt;
exit();
?>
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER