Get query results in array of arrays using json_encode in php - php

I am trying to fetch the list of id's associated with mobile number using following code.
$sql = "SELECT id FROM complaints WHERE mobile=1555521555";
$r = mysqli_query($conn,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"id"=>$res['id']
)
);
header('Content-Type:application/json');
echo json_encode(array("result"=>$result));
mysqli_close($conn);
But it only result me a single id every time as below instead of list of id's
{"result":[{"id":"82925318"}]}
Actual query result is -
How do I get the multiple results in array of arrays format or in multidimensional array? Like below -
{"result":[{"id":"82925318"}, {"id":"82925319"}]}

You need loop to get all data
$result = array();
while($res = mysqli_fetch_array($r))
{
array_push($result,array(
"id"=>$res['id']
)
);
}

Related

how i can use JSON result in calculation in php

i want to use json result in some calculation but whatever i try it didn't work.
<?php
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2);
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
// "gp_id"=>$row['gp_id'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
//calculate avg rate of specific product
$avg_rate = (int)"total_rate" / (int)"consumer";
echo $avg_rate ;
?>
as you see at the end i try to do some calculation but it didn't work.
this is the output...
[{"total_rate":"18","consumer":"4"}]
Warning: Division by zero in C:\xampp\htdocs\totalrate\highRate.php on line 33
$objJson=json_encode($res); makes json string. For example '{"a":1,"b":2,"c":3,"d":4,"e":5}'. You cannot use it like variables. Its string.
$avg_rate = "total_rate" / "consumer";
Looks like you trying to divide a string with another string.
Try using the array element instead, like:
$avg_rate = $res["total_rate"] / $res["consumer"];
finally i solve the problem ...
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2) or die(mysql_error());
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
"avg_rate"=>$row['total_rate']/ $row['consumer'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
?>

Array_push is only giving one value from an sql query?

I have an sql query which is fetching the data in format :
Date comment
12-3-2016 local meeting
and so-on..
I am using array_push for values so that i can display them in a page but i am only getting one value value from using array_push. here is my code:
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"Date"=>$res['date'],
"Events"=>$res['comment']
)
);
//using JSON
echo json_encode(array("result"=>$result));
mysqli_close($con);
The output which i am getting is like this:
{"result": [{"Date": "12-3-2016","Events": "Parent Teacher Meeting"}]}
mysqli_fetch_array($r) fetches one row from a result set. To get all rows from a result set, you should use while-loop:
$result = array();
while($res = mysqli_fetch_array($r)) { // here, a while-loop
array_push($result,array(
"Date" => $res['date'],
"Events" => $res['comment']
));
}
//using JSON
echo json_encode(array("result"=>$result));
mysqli_close($con);

Easily add data from database to multidimensional array using php

How can I easily add data from MySQL to a multidimensional array in PHP? I am making a search box and I want to store the first name, and the last name in the array.
Why does not this work.
$result = mysqli_query($db, $sql) or die(mysqli_error());
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[$row['primary']] = $row['firstname'], $row['lastname'];
}
$data[$row['primary']] = array($row['firstname'], $row['lastname']);

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Retrieving a database record set into an array in php

I want to retrieve a set of records from a MySQL table as an array.
So far I was able to retrieve each row as an associative array. But I want all the rows in one array because I have to access that complete object in jQuery to display them.
This is what I have done so far.This is my .php script to retrieve data
//select query
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
$numRows = mysql_num_rows($result); //to iterate the for loop
//passing as an associative array
for ($count = 0; $count < $numRows; $count++){
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo json_encode($row);
}
This is what I currently get
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"}
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"}
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"}
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
But I want this result set as follows.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
I seek help in doing this. Thanks in advance.
Put it all in one array, then json_encode it:
$json = array( );
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$json[] = $row;
}
echo json_encode( $json );
FYI: there's no need to count the number of results to loop. mysql_fetch_* will internally keep a pointer to the current record and increment that on each call. That makes it a perfect candidate to use in a simple while loop. Also, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc instead, a method I much prefer. Makes the code easier to read too (in my opinion, anyway).

Categories