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?
something like this:
function recordSetToJson($recordset) {
while($rs1 = mysql_fetch_row($recordset)) {
for($count = 0; $count < count($rs1); $count++) {
// read and add field to JSON
}
$count++;
}
return $jasonstring
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With