getting correct json response - php

I am getting data from database and showing it in form of json
Here is how I do:
while ($row = #mysqli_fetch_row($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode($result1,true);
which gives result in this form
[["29"],["13702210"],["892344"],["Multi AxleB9RVolvo"],["10:30AM"],["06:45PM"],["14"],["37"],["650"]]
This prints only the database value fetching from table. But this response marked as invalid json response
Each of the fields has name in table.
I want to see json response in this form:;
{"routes":[{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}},{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}},{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}}]}
This contains name and nested preview. How can I do this?

I don't know the strucutre of your database, but:
while ($row = #mysqli_fetch_assoc($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode(array('routes' => $result1));
May give you the result you want. mysql_fetch_assoc() returns the table rows as associative arrays which will provide keys.
Then array('routes' => $result1) creates a new associative array with the key 'routes' matching your index of arrays.
If they keys aren't correct in your sql response you could try using select field_name as alias_name in your SQL query to return the appropriate field names.
The real trick here is setting up associative arrays with appropriate keys for each value so that json_encode creates objects rather than lists.

You need to use associative array, use this;
while ($row = #mysqli_fetch_assoc($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode($result1,true);
// for `routes` parent
// echo $result1 = json_encode(array("routes" => $result1));

Related

How can i create a array with arrays created from db using fetch?

Edit:
I found a answer, so if we have to loop twice and create array inside array just do:
$data1=array_merge($data1,$result->fetch_all(MYSQLI_ASSOC));
my structure need to look like that:
['some':[{'num1':1,'num2':2},{'num1':10, 'num2':20}],'nextOne':[{'num1':1,'num2':2},{'num1':10, 'num2':20}],..... (and more...)
I have to create json data from around 4k records so i separate main data and i did something like that:
$data1 = array();
$data2 = array();
//etc.. up to 14 records
I had one existing table but i also create next with main separators, for separate data so for example:
$sql1 = "SELECT some.tit AS Title,someExtra.sub AS SubTitle FROM some INNER JOIN someExtra ORDER BY orderNr";
$result1 = $conn->query($sql1);
while($row = $result1->fetch_assoc()){
$myData = $row["Title"];
$my2ndData = $row["SubTitle "];
And now i need to find that data in next table and pass it to my array so..
$sql2 = "SELECT * FROM main WHERE expect = '$myData' AND expect2 = $my2ndData";
$result2 = $conn->query($sql2);
if($myData == 'That i need'){
$data1+=$result2->fetch_all(MYSQLI_ASSOC);
So like in example we have 2 loops, if we will have for example few records in 'someExtra' table that will match 'some' table will look next one for example : 4 times.. So if i will echo number of results inside my array just before i will send it to right array i will have 4,22,1,55,33 record in each. But on end of a script when i will count array i will heave only 33 records instead of have 115.
Also i try
array_push($data1, $result2->fetch_all(MYSQLI_ASSOC));
But that one doesynt work eather, becouse it add arrays with values to existing array... so i will have array in array in array with is not that i wont.
My final output look like that:
$outp=array('some'=>$data1,'AnextOne'=>$data2)
$myJSON = json_encode($outp, JSON_NUMERIC_CHECK);
After few hour of trying i solve the issue.
So if you will have to transfer your data from database in to json format, and separate your data by specifying keys. just do:
$data1=array_merge($data1,$result->fetch_all(MYSQLI_ASSOC));
Where:
$data1 - name of your 1st array (value for key number 1)
$result->fetch_all(MYSQLI_ASSOC) - array format where key is a row name and value is your data from row.
array_merge - that will connect your new array with old one without creating other arrays inside existing one.

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

column counterpart to mysql_fetch_array() in PHP

I am new to PHP and looking for some help.
I read a column of data from a table in a database and send the data to a dropdown menu in the form of an array.
Now, the function mysql_fetch_array() converts a row of data into an array. I tried using the same function on a column with improper results.
Is there a function that similarly converts a column of data into an array?
You could simple iterate over the result(-rows) and get your column array if you like:
$columnArrays = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
foreach ($row AS $key=>$value){
if (isset($columnArrays[$key]))
$columnArrays[$key][] = $value; //add to existing array
else
$columnArrays[$key] = array($value); //create new array
}
}
Now you have all ids (depending on the column name) in $columnArrays["id"] - all names in $columnArrays["name"] and so on.

Looping through resultings record and getting duplicates in foreach

So I am trying what I feel is a simply loop through a record result. My query returns one row of data. I am attempting to simply pull the value of each row from the returning record into a variable called $questions. However, my var $questions when printed out has duplicates in every space. It should read something like Bob|Ted|Joe|Sally and instead it is reading Bob|Bob|Ted|Ted|Joe|Joe|Sally|Sally. Why is the code below running twice in the foreach loop?
while ($row = mssql_fetch_array($result)){
foreach ($row as $col => $value) {
$questions.=$value."|";
}
}
echo "Questions: ".$questions."<br/>";
Here is all you need to do:
$questions = "";
while ($row = mssql_fetch_array($result)){
$questions .= $row['fieldName']."|";
}
echo "Questions: ".$questions."<br/>";
The foreach() in addition to the while() is unnecessary.
The mssql_fetch_array according to PHP doc:
In addition to storing the data in the numeric indices of the result
array, it also stores the data in associative indices, using the field
names as keys.
The result includes a normal array [0...n] with one element for each column, but also an associative array where each value is represented by a key named after the column name.
So if your first column is Id, you could get id from a row in two ways:
$id = $row[0];
# or you could do this
$id = $row['Id'];
This is why you get each value twice when looping through row.

Disappear the arrays generated with mysql_fetch_array() after use?

I have a typical database query:
$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');
and I can convert it in an array and print the data:
while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;
but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?
Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.
$data = array();
while($results = mysql_fetch_array($query)) {
$data[] = $results;
}
foreach ($data as $result_row) {
echo $result_row['referencia'];
... etc.
}
Try this
while($results = mysql_fetch_array($query))
{
$data[] = $results;
}
Now, all of your results are in $data, and you can do whatever you want from there.
As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got

Categories