Get all mysql selected rows into an array - php

I am wondering if there a function in php that can allow me put all my selected data in an array .Currently i am using mysql_fetch_array and as i have read in the manual,that function won't fetch every record in the table.
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_array($result);
echo json_encode($array);

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:
while($row = mysql_fetch_assoc($result)){
$json[] = $row;
}
echo json_encode($json);
If you switched to MySQLi you could do:
$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);
$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

Loop through the results and place each one in an array
use mysqli_fetch_all() to get them all at one time

You could try:
$rows = array();
while($row = mysql_fetch_array($result)){
array_push($rows, $row);
}
echo json_encode($rows);

$name=array();
while($result=mysql_fetch_array($res)) {
$name[]=array('Id'=>$result['id']);
// here you want to fetch all
// records from table like this.
// then you should get the array
// from all rows into one array
}

This method is also very nice, you can try it.
try {
while ($row=mysqli_fetch_array($res)) {
array_push($row...);
}
} catch (Exception $e) {
print($e->getMessage());
}

you can call mysql_fetch_array() for no_of_row time

Related

How can I format the sqli response in php into json? [duplicate]

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.
Try this, this will create your object properly
$result = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['object_name'][] = $r;
}
print json_encode($rows);
http://www.php.net/mysql_query says "mysql_query() returns a resource".
http://www.php.net/json_encode says it can encode any value "except a resource".
You need to iterate through and collect the database results in an array, then json_encode the array.
When using PDO
Use fetchAll() to fetch all rows as an associative array.
$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When your SQL has parameters:
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = [];
foreach ($stmt as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysqli
Use fetch_all() to fetch all rows as an associative array.
$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When your SQL has parameters you need to perform prepare/bind/execute/get_result.
$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
foreach ($res as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysql_* API
Please, upgrade as soon as possible to a supported PHP version! Please take it seriously. If you need a solution using the old API, this is how it could be done:
$res = mysql_query("SELECT * FROM article");
$rows = [];
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row;
}
echo json_encode($rows);
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
} else {
echo "0 results";
}
The code below works fine here!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
The above will not work, in my experience, before you name the root-element
in the array to something, I have not been able to access anything in the
final json before that.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
That should do the trick!
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', 'dishant');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql = "select * from demo ";
$sth = mysqli_query($con, $sql);
$rows = array();
while ($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
$row_array['id'] = $r;
array_push($rows, $row_array);
}
echo json_encode($rows);
array_push($rows,$row_array); helps to build an array otherwise it gives the last value in the while loop.
This works like append method of StringBuilder in Java.
My simple fix to stop it putting speech marks around numeric values...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
Sorry, this is extremely long after the question, but:
$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]")
AS json
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);
Just basically:
"SELECT" Select the rows
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
One more option using FOR loop:
$sth = mysql_query("SELECT ...");
for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
print json_encode($rows);
The only disadvantage is that loop for is slower then e.g. while or especially foreach
For example
$result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");
1.) if $result is only one row.
$response = mysql_fetch_array($result);
echo json_encode($response);
2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.
$rows = array();
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["USERID"]; //a column name (ex.ID) used to get a value of the single row at at time
$rows[$id] = $r; //save the fetched row and add it to the array.
}
}
echo json_encode($rows);
I solved like this
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
This will be returned to ajax as result set
and by using json parse in javascript part like this :
obj = JSON.parse(dataX);
we could simplify Paolo Bergantino answer like this
$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
We shouldn't see any use of mysql_ functions in modern applications, so either use mysqli_ or pdo functions.
Explicitly calling header("Content-type:application/json"); before outputting your data payload is considered to be best practice by some devs. This is usually not a requirement, but clarifies the format of the payload to whatever might be receiving it.
Assuming this is the only data being printed, it is safe to print the json string using exit() which will terminate the execution of the script as well. This, again, is not essential because echo will work just as well, but some devs consider it a good practice to explicitly terminate the script.
MySQLi single-row result set from query result set object:
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from query result set object:
Prior to PHP 8.1.0, available only with mysqlnd.
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
MySQLi single-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from query result set object:
exit(json_encode($result->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from query result set object:
exit(json_encode($result->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from prepared statement:
exit(json_encode($stmt->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from prepared statement:
exit(json_encode($stmt->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
Obey these rules to prevent the possibility of generating invalid json.:
you should only call json_encode() after you are completely finished manipulating your result array and
you should always use json_encode() to encode the payload (avoid the urge to manually craft a json string using other string functions or concatenation).
If you need to iterate your result set data to run php functions or provide functionality that your database language doesn't offer, then you can immediately iterate the result set object with foreach() and access values using array syntax -- e.g.
$response = [];
foreach ($result as $row) {
$row['col1'] = someFunction($row['id']);
$response[] = $row;
}
exit(json_encode($response));
If you are calling json_encode() on your data payload, then it won't make any difference to whether the payload is an array of arrays or an array of objects. The json string that is created will have identical syntax.
You do not need to explicitly close the database connection after you are finished with the connection. When your script terminates, the connection will be closed for you automatically.
Considering there's not really any NESTED json objects in mysql in general etc., it's fairly easy to make your own encoding function
First, the function to retrieve the mysqli results in an array:
function noom($rz) {
$ar = array();
if(mysqli_num_rows($rz) > 0) {
while($k = mysqli_fetch_assoc($rz)) {
foreach($k as $ki=>$v) {
$ar[$ki] = $v;
}
}
}
return $ar;
}
Now, function to encode array as json:
function json($ar) {
$str = "";
$str .= "{";
$id = 0;
foreach($ar as $a=>$b) {
$id++;
$str .= "\"".$a."\":";
if(!is_numeric($b)) {
$str .= "\"".$b."\"";
} else {
$str .= $b;
}
if($id < count($ar)) {
$str .= ",";
}
}
$str .= "}";
return $str;
}
Then to use it:
<?php
$o = new mysqli(
"localhost",
"root",""
);
if($o->connect_error) {
echo "DUDE what are you/!";
} else {
$rz = mysqli_query($o,
"SELECT * FROM mydatabase.mytable"
);
$ar = noom($rz);
echo json($ar);
}
?>

Printing SQL Query output in PHP in JSON encoding [duplicate]

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.
Try this, this will create your object properly
$result = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['object_name'][] = $r;
}
print json_encode($rows);
http://www.php.net/mysql_query says "mysql_query() returns a resource".
http://www.php.net/json_encode says it can encode any value "except a resource".
You need to iterate through and collect the database results in an array, then json_encode the array.
When using PDO
Use fetchAll() to fetch all rows as an associative array.
$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When your SQL has parameters:
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = [];
foreach ($stmt as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysqli
Use fetch_all() to fetch all rows as an associative array.
$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When your SQL has parameters you need to perform prepare/bind/execute/get_result.
$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
foreach ($res as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysql_* API
Please, upgrade as soon as possible to a supported PHP version! Please take it seriously. If you need a solution using the old API, this is how it could be done:
$res = mysql_query("SELECT * FROM article");
$rows = [];
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row;
}
echo json_encode($rows);
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
} else {
echo "0 results";
}
The code below works fine here!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
The above will not work, in my experience, before you name the root-element
in the array to something, I have not been able to access anything in the
final json before that.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
That should do the trick!
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', 'dishant');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql = "select * from demo ";
$sth = mysqli_query($con, $sql);
$rows = array();
while ($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
$row_array['id'] = $r;
array_push($rows, $row_array);
}
echo json_encode($rows);
array_push($rows,$row_array); helps to build an array otherwise it gives the last value in the while loop.
This works like append method of StringBuilder in Java.
My simple fix to stop it putting speech marks around numeric values...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
Sorry, this is extremely long after the question, but:
$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]")
AS json
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);
Just basically:
"SELECT" Select the rows
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
One more option using FOR loop:
$sth = mysql_query("SELECT ...");
for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
print json_encode($rows);
The only disadvantage is that loop for is slower then e.g. while or especially foreach
For example
$result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");
1.) if $result is only one row.
$response = mysql_fetch_array($result);
echo json_encode($response);
2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.
$rows = array();
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["USERID"]; //a column name (ex.ID) used to get a value of the single row at at time
$rows[$id] = $r; //save the fetched row and add it to the array.
}
}
echo json_encode($rows);
I solved like this
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
This will be returned to ajax as result set
and by using json parse in javascript part like this :
obj = JSON.parse(dataX);
we could simplify Paolo Bergantino answer like this
$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
We shouldn't see any use of mysql_ functions in modern applications, so either use mysqli_ or pdo functions.
Explicitly calling header("Content-type:application/json"); before outputting your data payload is considered to be best practice by some devs. This is usually not a requirement, but clarifies the format of the payload to whatever might be receiving it.
Assuming this is the only data being printed, it is safe to print the json string using exit() which will terminate the execution of the script as well. This, again, is not essential because echo will work just as well, but some devs consider it a good practice to explicitly terminate the script.
MySQLi single-row result set from query result set object:
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from query result set object:
Prior to PHP 8.1.0, available only with mysqlnd.
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
MySQLi single-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from query result set object:
exit(json_encode($result->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from query result set object:
exit(json_encode($result->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from prepared statement:
exit(json_encode($stmt->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from prepared statement:
exit(json_encode($stmt->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
Obey these rules to prevent the possibility of generating invalid json.:
you should only call json_encode() after you are completely finished manipulating your result array and
you should always use json_encode() to encode the payload (avoid the urge to manually craft a json string using other string functions or concatenation).
If you need to iterate your result set data to run php functions or provide functionality that your database language doesn't offer, then you can immediately iterate the result set object with foreach() and access values using array syntax -- e.g.
$response = [];
foreach ($result as $row) {
$row['col1'] = someFunction($row['id']);
$response[] = $row;
}
exit(json_encode($response));
If you are calling json_encode() on your data payload, then it won't make any difference to whether the payload is an array of arrays or an array of objects. The json string that is created will have identical syntax.
You do not need to explicitly close the database connection after you are finished with the connection. When your script terminates, the connection will be closed for you automatically.
Considering there's not really any NESTED json objects in mysql in general etc., it's fairly easy to make your own encoding function
First, the function to retrieve the mysqli results in an array:
function noom($rz) {
$ar = array();
if(mysqli_num_rows($rz) > 0) {
while($k = mysqli_fetch_assoc($rz)) {
foreach($k as $ki=>$v) {
$ar[$ki] = $v;
}
}
}
return $ar;
}
Now, function to encode array as json:
function json($ar) {
$str = "";
$str .= "{";
$id = 0;
foreach($ar as $a=>$b) {
$id++;
$str .= "\"".$a."\":";
if(!is_numeric($b)) {
$str .= "\"".$b."\"";
} else {
$str .= $b;
}
if($id < count($ar)) {
$str .= ",";
}
}
$str .= "}";
return $str;
}
Then to use it:
<?php
$o = new mysqli(
"localhost",
"root",""
);
if($o->connect_error) {
echo "DUDE what are you/!";
} else {
$rz = mysqli_query($o,
"SELECT * FROM mydatabase.mytable"
);
$ar = noom($rz);
echo json($ar);
}
?>

PHP and MySqli getting all results

I have 2 rows of data in my database and I am trying to fetch all rows
$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$results = mysqli_fetch_assoc($query);
I have tried mysqli_fetch_assoc, mysqli_fetch_row, mysqli_fetch_array all of them just return 1 row of data.
mysqli_fetch_*() functions except mysqli_fetch_all(), if supported, fetch one row. Loop and fetch:
while($row = mysqli_fetch_assoc($query)) {
print_r($row);
//or you can echo $row['username'] etc...
//or store in an array to loop through later
$rows[] = $row;
}
If you use mysqlnd there is a mysqli_fetch_all() or use:
if(!function_exists('mysqli_fetch_all')) {
function mysqli_fetch_all($result, $resulttype=MYSQLI_BOTH) {
while($row = mysqli_fetch_array($result, $resulttype)) {
$rows[] =$row;
}
return $rows;
}
}
$results = mysqli_fetch_all($query);
But then you have to loop through all the returned rows anyway:
foreach($results as $row) {
print_r($row);
//or you can echo $row['username'] etc...
}
Switch to PDO to do it in a single go... Use PDOStatement::fetchAll
<?php
//.. Do the neccessary PDO connections...
$sth = $dbh->prepare("select username, email, is_admin from adminUsers");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
(or)
You need to loop through them... [MySQLi]
$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$res = array();
while($results = mysqli_fetch_assoc($query))
{
$res[] = $results;
}
print_r($res);
Use while loop for fetching all lines:
while ($result = mysqli_fetch_assoc($query))
{
// Rest of your code. See an example below
echo $result['username'];
}

PHP: filtering mysql_query result for specific column?

Is there a quick way to filter a mysql_query result to get a list containing only values of a specific column?
$query = mysql_query("SELECT * FROM users");
$list_of_user_names = get_values($query,"names");
What is the name of the function to be used in place of get_values?
Assuming your field name in databse is "names"
$query = mysql_query("SELECT names FROM users");
while($row = mysql_fetch_assoc($query)){
echo $row['names'];
echo "<br>";
}
NOTE : mysql_* functions are deprecated in new version of php, use mysqli_* or PDO
Use below function.
function get_values($q,$c)
{
$arr = array();
while($row = mysql_fetch_array($q))
{
$arr[] = $row[$c];
}
return $arr; // return all names value.
}
Try this:
$query = mysql_query("SELECT names FROM users");
if (!$query) {
echo "Could not successfully run query from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $names
while ($row = mysql_fetch_assoc($query)) {
echo $row["names"];
}

JSON encode MySQL results

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.
Try this, this will create your object properly
$result = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['object_name'][] = $r;
}
print json_encode($rows);
http://www.php.net/mysql_query says "mysql_query() returns a resource".
http://www.php.net/json_encode says it can encode any value "except a resource".
You need to iterate through and collect the database results in an array, then json_encode the array.
When using PDO
Use fetchAll() to fetch all rows as an associative array.
$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When your SQL has parameters:
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = [];
foreach ($stmt as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysqli
Use fetch_all() to fetch all rows as an associative array.
$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When your SQL has parameters you need to perform prepare/bind/execute/get_result.
$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
When you need to rekey the table you can use foreach loop and build the array manually.
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
foreach ($res as $row) {
$rows[] = [
'newID' => $row['id'],
'Description' => $row['text'],
];
}
echo json_encode($rows);
When using mysql_* API
Please, upgrade as soon as possible to a supported PHP version! Please take it seriously. If you need a solution using the old API, this is how it could be done:
$res = mysql_query("SELECT * FROM article");
$rows = [];
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row;
}
echo json_encode($rows);
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
} else {
echo "0 results";
}
The code below works fine here!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
The above will not work, in my experience, before you name the root-element
in the array to something, I have not been able to access anything in the
final json before that.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
That should do the trick!
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', 'dishant');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql = "select * from demo ";
$sth = mysqli_query($con, $sql);
$rows = array();
while ($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
$row_array['id'] = $r;
array_push($rows, $row_array);
}
echo json_encode($rows);
array_push($rows,$row_array); helps to build an array otherwise it gives the last value in the while loop.
This works like append method of StringBuilder in Java.
My simple fix to stop it putting speech marks around numeric values...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
Sorry, this is extremely long after the question, but:
$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]")
AS json
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);
Just basically:
"SELECT" Select the rows
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
One more option using FOR loop:
$sth = mysql_query("SELECT ...");
for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
print json_encode($rows);
The only disadvantage is that loop for is slower then e.g. while or especially foreach
For example
$result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");
1.) if $result is only one row.
$response = mysql_fetch_array($result);
echo json_encode($response);
2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.
$rows = array();
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["USERID"]; //a column name (ex.ID) used to get a value of the single row at at time
$rows[$id] = $r; //save the fetched row and add it to the array.
}
}
echo json_encode($rows);
I solved like this
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
This will be returned to ajax as result set
and by using json parse in javascript part like this :
obj = JSON.parse(dataX);
we could simplify Paolo Bergantino answer like this
$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
We shouldn't see any use of mysql_ functions in modern applications, so either use mysqli_ or pdo functions.
Explicitly calling header("Content-type:application/json"); before outputting your data payload is considered to be best practice by some devs. This is usually not a requirement, but clarifies the format of the payload to whatever might be receiving it.
Assuming this is the only data being printed, it is safe to print the json string using exit() which will terminate the execution of the script as well. This, again, is not essential because echo will work just as well, but some devs consider it a good practice to explicitly terminate the script.
MySQLi single-row result set from query result set object:
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from query result set object:
Prior to PHP 8.1.0, available only with mysqlnd.
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
MySQLi single-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_assoc())); // 1-dimensional / flat
MySQLi multi-row result set from prepared statement:
$result = $stmt->get_result();
exit(json_encode($result->fetch_all(MYSQLI_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from query result set object:
exit(json_encode($result->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from query result set object:
exit(json_encode($result->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
PDO single-row result set from prepared statement:
exit(json_encode($stmt->fetch(PDO::FETCH_ASSOC))); // 1-dimensional / flat
PDO multi-row result set from prepared statement:
exit(json_encode($stmt->fetchAll(PDO::FETCH_ASSOC))); // 2-dimensional / array of rows
Obey these rules to prevent the possibility of generating invalid json.:
you should only call json_encode() after you are completely finished manipulating your result array and
you should always use json_encode() to encode the payload (avoid the urge to manually craft a json string using other string functions or concatenation).
If you need to iterate your result set data to run php functions or provide functionality that your database language doesn't offer, then you can immediately iterate the result set object with foreach() and access values using array syntax -- e.g.
$response = [];
foreach ($result as $row) {
$row['col1'] = someFunction($row['id']);
$response[] = $row;
}
exit(json_encode($response));
If you are calling json_encode() on your data payload, then it won't make any difference to whether the payload is an array of arrays or an array of objects. The json string that is created will have identical syntax.
You do not need to explicitly close the database connection after you are finished with the connection. When your script terminates, the connection will be closed for you automatically.
Considering there's not really any NESTED json objects in mysql in general etc., it's fairly easy to make your own encoding function
First, the function to retrieve the mysqli results in an array:
function noom($rz) {
$ar = array();
if(mysqli_num_rows($rz) > 0) {
while($k = mysqli_fetch_assoc($rz)) {
foreach($k as $ki=>$v) {
$ar[$ki] = $v;
}
}
}
return $ar;
}
Now, function to encode array as json:
function json($ar) {
$str = "";
$str .= "{";
$id = 0;
foreach($ar as $a=>$b) {
$id++;
$str .= "\"".$a."\":";
if(!is_numeric($b)) {
$str .= "\"".$b."\"";
} else {
$str .= $b;
}
if($id < count($ar)) {
$str .= ",";
}
}
$str .= "}";
return $str;
}
Then to use it:
<?php
$o = new mysqli(
"localhost",
"root",""
);
if($o->connect_error) {
echo "DUDE what are you/!";
} else {
$rz = mysqli_query($o,
"SELECT * FROM mydatabase.mytable"
);
$ar = noom($rz);
echo json($ar);
}
?>

Categories