Convert MySQL record set to JSON string in PHP
This should work:
function recordSetToJson($mysql_result) {
$rs = array();
while($rs[] = mysql_fetch_assoc($mysql_result)) {
// you don´t really need to do anything here.
}
return json_encode($rs);
}
If you need to manipulate the result set you can use the following -more complex- version that lets you add a callback function that will be called on every record and must return that record already processed:
function recordSetToJson($mysql_result, $processing_function = null) {
$rs = array();
while($record = mysql_fetch_assoc($mysql_result)) {
if(is_callable($processing_function)){
// callback function received. Pass the record through it.
$processed = $processing_function($record);
// if null was returned, skip that record from the json.
if(!is_null($processed)) $rs[] = $processed;
} else {
// no callback function, use the record as is.
$rs[] = $record;
}
}
return json_encode($rs);
}
use it like this:
$json = recordSetToJson($results,
function($record){
// some change you want to make to every record:
$record["username"] = strtoupper($record["username"]);
return $record;
});
Is there a function or class in PHP that I can pass a MySQL recordset and I get a JSON string returned that can be passed back to a JavaScript function in an Ajax request?
Yes: json_encode()