Having trouble while encoding json Array in php - php

I have two different queries which I have to append in same array in form of JSON..
Here is my code from 1st query...
while($row = mysqli_fetch_array($res)) {
array_push($result,array('name'=>$row[0],'photo'=>$row[1],'rollno'=>$row[2],'id'=>$row[3]));
}
Here is my second query push similar as first one.. number of rows is always same as above query
array_push($result,array('status'=>'$status');
After that I'm encoding them like this
echo json_encode(array("result"=>$result));
Here is what I am getting
{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26"},
{"status":"status"}]
But I want to result like this
{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26","status":"status"}]
I mean status will merge into my every node... how can I achieve this..?

Try the below to add status field to each array:
while($row = mysqli_fetch_array($res)){
array_push($result,array('name'=>$row[0],'photo'=>$row[1],'rollno'=>$row[2],'id'=>$row[3]));
}
$res_row = 0;
while($row2 = mysqli_fetch_array($res2)){
$status = $row2[0]; // status value here
$result[$res_row]['status']=$status;
$res_row++;
}
echo json_encode(array("result"=>$result));

Try this please, using temporary arrays that are merged after all your queries are complete:
// Query 1
while($row = mysqli_fetch_array($res)){
$tmpResults[] = $row;
}
// Query 2
$tmpResult2 = array('status'=>'$status');
// Merge Everything
$final = array_merge($tmpResults, $tmpResult2);
// Encode
$json = json_encode($final, TRUE);
Good luck

Related

How do I convert database query result to JSON contained in one single array?

I'm attempting to create a web app that displays records in my record collection stored in a database. I want to pull the rows from the database, convert them to JSON, then with Javascript write the JSON objects to an HTML page. Currently I have a php while loop writing the rows to an array..
<?php
include('./connection.php');
$query = "SELECT * FROM voting";
$result = $mysqli->query($query);
if (!$result) die($mysqli->error);
$array = array();
while ($row = $result->fetch_object()) {
$array[] = $row;
echo json_encode($array);
} ?>
The while loop is writing each row to it's own array. I want to place all of the returned JSON objects into one array. How do I achieve this?
php:
$array = array();
while ($row = $result->fetch_object()) {
$array[] = $row;
}
javascript:
<script>
var data = <?php echo json_encode($array, JSON_HEX_TAG); ?>;
</script>
console.log(data);

Php append value to an exsisting array

Hi I need to add some value-key pair to an array which is the output of mysql query. Below is the code,
$query = "select TITLE,DESCRIPTION from TABLE where ID='1234'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
if($numrows>0)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
Giving me the result like
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION."}]
Now I need to to add an another key-value pair to generate the json output like,
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION.","URL":"imgname.jpg"}]
So I added the code
$myArray["URL"]="imgname.jpg";
echo json_encode($myArray);
But giving me the output like,
{"0":{"TITLE":"Chef Special","DESCRIPTION":"Grilled Salmon and crab."},"URL":"imgname.jpg"}
Is there anything wrong with above code.
check your data with
var_dump($myArray);
and you will find, that it is a 2-dimensional array. you'd have to add your data with
$myArray[0]["URL"] = "imgname.jpg";
If you have to add after encoding it, reverse with:
$a = json_decode($myArray,true)
add a new pair of key, value with $a['URL'] = "imgname.jpg" and then encode again.

JSON and array structure typeahead

I am trying to create a json file from an sql query, and search this json using twitter typeahead. However the json format doesn't look correct.
The json needs to be in a certain format for typeahead like below;
['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California' ...];
However my json is in the following format;
["{\"title\":\"Item 1\"}","{\"title\":\"Item 2\"}","{\"title\":\"Item 3\"}"
Newbie to php/sql/json I'm sure there is something really obvious I'm missing or doing wrong. Maybe I should be using a foreach and not while? I am able to echo out the $titles so I now the query is working.
If somebody cold point me in the right direction I would appreciate it.
My code so far;
$sql = ("SELECT title FROM publication");
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
$data = array();
while($row = $result->fetch_assoc()){
$data[] = json_encode($row);
$titles = json_encode($data);
echo $titles;//for testing
}
file_put_contents('titles.json', $titles);
You're over-encoding your data and
you're not including the data you actually want.
Put the data you want into the array and JSON-encode the whole thing only at the end:
while ($row = $result->fetch_assoc()) {
$data[] = $row['title'];
}
file_put_contents('titles.json', json_encode($data));
You are performing json_encode twice which should not be the case.
Instead the Code should be like below:
$data[] = $row;
$titles = json_encode($data);
or simply
$titles = json_encode($row);
Use json_encode once
$data[] = $row; /*$data[] = json_encode($row);*/
and write this:
$titles = json_encode($data);
OR
$titles = json_encode(array_values($data)); /*You may need to use this to get exact output*/
After while loop
You are inserting associative array to your json array('title'=>'sometitle') but you only need that title.
The solution is to only save the title value from the db resulting row to the array:
while($row = $result->fetch_assoc()){
$data[] = $row['title'];
echo json_encode($data); // dont encode twice
}
file_put_contents('titles.json', json_encode($data));

json showing duplicate output of mysql result

I am trying to print json_encode and I get output duplicated. I am certain there is one single record in database and yet it shows the same record data twice in various format. This is it:
[{"0":"Polo","name":"Polo","1":"City ","location":"City ","2":"Manama","city":"Manama"}]
The code behind this is:
$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
Any idea?
This is because the default behavior of mysql_fetch_array() is to return both a column name and index keyed array.
Use mysql_fetch_assoc() or set the second parameter of mysql_fetch_array().
while($r = mysql_fetch_assoc($result)) {
$dataArray[] = $r;
}
You should set another fetch style. It now fetches all columns using both their 0 based index and their name.
This should work as expected:
$dataArray = array();
while($r = mysql_fetch_array($result, MYSQL_ASSOC))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
You're getting this because you can access the results either by name or by column index, but you're serializing the entire thing, so both ways of getting the data are showing up.
try this
//$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
I commented first line. Because you used like that $dataArray[].

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

Categories