// 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;