Posted By

hasantayyar on 08/11/09


Tagged

json phpmysql


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

hasantayyar
vali29
irishsk
umang_nine
nerdfiles
farondomenicgmailcom
nb109
ringo380
catrinho


MySQL to JSON - PHP Class


 / Published in: PHP
 

URL: http://www.phpclasses.org/browse/file/14803.html

mysql2json.class.php

  1. <?
  2. /**
  3. * Filename: mysql2json.class.php
  4. * Purpose: Convert mysql resultset data into JSON(http://json.org) format
  5. * Author: Adnan Siddiqi <[email protected]>
  6. * License: PHP License
  7. * Date: Tuesday,June 21, 2006
  8. *
  9. */
  10.  
  11.  
  12. class mysql2json{
  13.  
  14. function getJSON($resultSet,$affectedRecords){
  15. $numberRows=0;
  16. $arrfieldName=array();
  17. $i=0;
  18. $json="";
  19. //print("Test");
  20. while ($i < mysql_num_fields($resultSet)) {
  21. $meta = mysql_fetch_field($resultSet, $i);
  22. if (!$meta) {
  23. }else{
  24. $arrfieldName[$i]=$meta->name;
  25. }
  26. $i++;
  27. }
  28. $i=0;
  29. $json="{\n\"data\": [\n";
  30. while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
  31. $i++;
  32. //print("Ind ".$i."-$affectedRecords<br>");
  33. $json.="{\n";
  34. for($r=0;$r < count($arrfieldName);$r++) {
  35. $json.="\"$arrfieldName[$r]\" : \"$row[$r]\"";
  36. if($r < count($arrfieldName)-1){
  37. $json.=",\n";
  38. }else{
  39. $json.="\n";
  40. }
  41. }
  42.  
  43.  
  44. if($i!=$affectedRecords){
  45. $json.="\n},\n";
  46. }else{
  47. $json.="\n}\n";
  48. }
  49.  
  50.  
  51.  
  52. }
  53. $json.="]\n};";
  54.  
  55. return $json;
  56. }
  57.  
  58.  
  59. }
  60. ?>

Report this snippet  

You need to login to post a comment.