tags:

views:

119

answers:

2

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
}
+3  A: 

Yes.

json_encode()

NullUserException
yes thank you. The trouble I was having was preparing a PHP array containing multiple mysql recordsets that can then be encoded.
TMP file guy
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.
TMP file guy
A: 

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);
}
Sebastián Grignoli
What if he wants to manipulate the result set somehow?
NullUserException
Sebastian's solution seems to work
TMP file guy
@NullUserException he shouldn't be using a function this generic then.
Sebastián Grignoli