Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MySQL record set to JSON string in PHP [duplicate]

Tags:

json

php

mysql

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
}
like image 839
TMP file guy Avatar asked Aug 07 '10 12:08

TMP file guy


2 Answers

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;
    });
like image 56
Sebastián Grignoli Avatar answered Nov 09 '22 16:11

Sebastián Grignoli


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()

like image 22
NullUserException Avatar answered Nov 09 '22 16:11

NullUserException