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));
Related
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
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[].
I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
Help would be much appreciated.
You need to loop through the results. mysql_fetch_row gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row.php
The code would end up like:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
PLEASE NOTE
The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above.
http://www.php.net/manual/en/mysqli-result.fetch-row.php
I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
Fetching results allowing edit on fields:
while( $row = odbc_fetch_array($result) ) {
$json['field_1'] = $row['field_1'];
$json['field_2'] = $row['field_2'];
$json['field_3'] = $row['field_1'] + $row['field_2'];
array_push($response, $json);
}
Or if i do not want to change anything i could simplify like this:
while ($array = odbc_fetch_array($result)) { $response[] = $array; }
What if i want to return the results in JSON format?, easy:
echo json_encode($response, true);
You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.
According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
so you need for example a while loop to fetch all rows:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
echo json_encode($rows);
I leave it to you how to only fetch 3 rows :)
You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.
See example:
http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794
$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");
$json = array();
while($array = mysql_fetch_row($result)){
$json[] = $array;
}
echo json_encode($json);
I'm trying to get the tag-it jquery plugin to work with a json string.
Currenttly i'm getting my values from the database like this:
$query = sprintf(
'SELECT
t.tag
FROM
tags AS t
');
$row_set= array();
if($result = mysqli_query($db, $query))
{
// fetch data
while ($row = mysqli_fetch_assoc($result))
{
$row_set[] = $row;
}
// set the output
echo json_encode($row_set);
}
which gives the following output when called in AJAX:
[{"tag":"test"},{"tag":"tests"}]
But I have to output a JSON string in the following format:
["android-intent","animate","architecture","artificial-intelligence","attributes"]
How can i achieve this?
When you use row_set[] = $row; most likely $row looks like this $row['tag'] = 'test that is why you are having JSON object format;
Try
$row_set[] = $row['tag'];
Make sure you also set the seound parameter to true to make JSON always return array
json_encode($row_set,true);
This would return the it as array not as a object
That should fix it, by adding string into you arrow instead of adding arrays into you array.
$row_set[] = $row[0]; or $row_set[] = $row['tag'];
HI i need to output a JSON object for consuming in iphone
i am able to output like
{"feed":{"id":"1","player":"player1"}}
{"feed":{"id":"1","player":"player2"}}
{"feed":{"id":"2","player":"player3"}}
The code :
$query = "SELECT id,player FROM MyVideos";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$players[] = array();
if(mysql_num_rows($result)){
while($player = mysql_fetch_assoc($result)){
$players[] = array('player'=>$player);
echo json_encode(array("feed"=>$player));
}
}
But i need to output some thing like this
{"feed":
{"id":"1","player":"player1"},
{"id":"1","player":"player2"},
{"id":"2","player":"player3"}
}
Can anyone please help me with this.
Thanks,
The output you posted isn't valid JSON, you need to put brackets around the items in feed:
{"feed": [
{"id":"1","player":"player1"},
{"id":"1","player":"player2"},
{"id":"2","player":"player3"}
]}
You should loop through your results and build an array of your feed items, and then output it all at once, like this:
$feed_items = array();
if (mysql_num_rows($result)) {
while ($player = mysql_fetch_assoc($result)){
$feed_items[] = $player;
}
}
echo json_encode(array("feed" => $feed_items));