Convert MySQL record set to JSON string in PHP [duplicate]
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()
I wanna put a little integration to @Sebastian code.
Please, don't make assignment in the while test condition, oterwhise the last check (the one that stop the loop and return false) whit put the false value in the array.
So, the right way is
function recordSetToJson($mysql_result) {
$rs = array();
while($row=mysql_fetch_assoc($mysql_result)) {
$rs[]=$row;
}
return json_encode($rs);
}
精彩评论