Return to Snippet

Revision: 4811
at January 21, 2008 23:59 by ecavazos


Initial Code
// query parameters
$p[0] = 'id';
$p[1] = 'name';

// query database
$result = $dal->selectFieldsOrder('inventory_categories', $p, 'name asc');

$numRows = $result->num_rows;
$loopCount = 1;

$json = '{ '
	  . '"categories" : [';

// build json string
while ($row = $result->fetch_assoc()) {
	$json .= '{ '
		  . '"id" : "' . $row['id'] . '", '
		  . '"name" : "' . addcslashes($row['name'], '"') . '" '
		  . '}';
	
	// add comma if 	  
	if ($loopCount < $numRows) {
		$json .= ', ';
		$loopCount++;
    }
}

$json .= '] '
	  . '}';

echo $json;

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

Initial Description
This snippet references the data access class I linked to.

Initial Title
Output JSON String from PHP

Initial Tags
php, json

Initial Language
PHP