6

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
}
0

3 Answers 3

14

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;
    });
Sign up to request clarification or add additional context in comments.

2 Comments

@NullUserException he shouldn't be using a function this generic then.
I added a version that allows you to process the records.
5

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

2 Comments

yes thank you. The trouble I was having was preparing a PHP array containing multiple mysql recordsets that can then be encoded.
I just found something that might work. www.barattalo.it/2010/01/25/10-php-usefull-functions-for-mysql-stuff/. ___ However I am not able to reference fields in javascript.
0

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.