Page 1 of 1

PHP returning JSON

Posted: Tue Feb 21, 2012 10:57 am
by jonatec
Hi

Please take a look at the code section. Does anyone know how to:
a) Return JSON from the prepared procedure call instead of me using a while loop and a concatenated string?
b) Given the MySQL query returns these columns: ID, DepartmentName how do I access these in my client-side JavaScript, ie what will the JSON look like ?

Many thanks.

Code: Select all

function fnGetDepartments() {

	require ('mysqli_connect.php'); // Connect to the Db.	
	$sql = "CALL get_departments(?)";
	$stmt = $dbc->prepare($sql);
	if ($dbc->errno) {die($dbc->errno.":: ".$dbc->error);}
	$stmt->bind_param("i", $prm);
	$stmt->execute( );
	if ($dbc->errno) {die($dbc->errno.": ".$dbc->error);}
	$stmt->bind_result($id, $dept_name);
	$buf = "";
	while ($stmt->fetch( )) {
		$buf .= $id . '^' . $dept_name . '|';
	}
	$buf = substr($buf, 0, strlen($buf)-1);
	echo $buf;	
	mysqli_close($dbc);
}

Re: PHP returning JSON

Posted: Tue Feb 21, 2012 6:17 pm
by Celauran
mysqli_result::fetch_all (or PDOStatement::fetchAll) + json_encode?