Output JSON String from PHP


/ Published in: PHP
Save to your folder(s)

This snippet references the data access class I linked to.


Copy this code and paste it in your HTML
  1. // query parameters
  2. $p[0] = 'id';
  3. $p[1] = 'name';
  4.  
  5. // query database
  6. $result = $dal->selectFieldsOrder('inventory_categories', $p, 'name asc');
  7.  
  8. $numRows = $result->num_rows;
  9. $loopCount = 1;
  10.  
  11. $json = '{ '
  12. . '"categories" : [';
  13.  
  14. // build json string
  15. while ($row = $result->fetch_assoc()) {
  16. $json .= '{ '
  17. . '"id" : "' . $row['id'] . '", '
  18. . '"name" : "' . addcslashes($row['name'], '"') . '" '
  19. . '}';
  20.  
  21. // add comma if
  22. if ($loopCount < $numRows) {
  23. $json .= ', ';
  24. $loopCount++;
  25. }
  26. }
  27.  
  28. $json .= '] '
  29. . '}';
  30.  
  31. echo $json;

URL: http://snipplr.com/view/4715/simple-data-access-class/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.