I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);
Related
i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;
I have this array
$data = [ 'admin'=>'1', 'natasha'=>'2', 'demo3'=>'3' ];
When I output it echo json_encode($data); I get {"admin":"1","natasha":"2","demo3":"3"} and this how I need it and it works well!
Now I'm trying to loop data from database like this:
$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row) {
$data[]= array($row->user_name=>$row->user_id);
}
header('Content-Type: application/json');
echo json_encode($data);
But I'm getting this format [{"demo4":"4"},{"demo3":"3"}] but I need {"admin":"1","natasha":"2","demo3":"3"}
I tried many things, pass strings and convert to array or manipulate array but none of it gave me the proper format. Any idea?
$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row) {
$data[$row->user_name] = $row->user_id;
}
header('Content-Type: application/json');
echo json_encode($data);
To achieve what you want, you need to set the name as the array key inside your foreach loop:
$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row)
{
$data[$row->user_name]= $row->user_id;
}
header('Content-Type: application/json');
echo json_encode($data);
And I suggest that you escape both key and value of your array to avoid unwanted characters, otherwise your json_encode will fail returning false.
A simply way to do it can be: str_replace("'", "", $row->user_name) and str_replace("'", "", $row->user_id).
i'm new in PHP language. I'm writing a PHP script to get information from my online database(created on my altervista personal webpage) and convert in JSON format.
The problem is about when i get elements from my database i can show them correctly using "echo" command, but when i parse associative array to "json_encode" function i can't see correctly elements.
Here is the code:
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
foreach($row as $key => $value) {
echo "" . $key . ": " . $value;
echo "<br>";
$json_array[] = array(''=>$key, ''=>$value);
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
?>
The $result->fetch_assoc(); returns an associative array.
As i said before i can see correct information using echo commands.
The problem is when i use this:
$json_array[] = array(''=>$key, ''=>$value);
The output is as follow:
[{"":"Mark"},{"":"ABC"},{"":"25"}]
Basically it's showing me only the second parameter "=>$value", while the first parameter "=>$key" is ignored.
Can you tell me please what should i change in order to see also the first parameter in my output?
Thanks
The correct way would be to do that
$json_array[] = array( $key => $value );
instead of
$json_array[] = array(''=>$key, ''=>$value);
You are essentially adding an EMPTY string as key and the $key as value at first, and then you replace it with the $value as they share the EMPTY string key in the array.
Read more at: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.array-func
First param is ignored because it has the same key as the second (the key is ''), you should write:
$json_array[] = array($key, $value); // Indexed array
Output will be:
[["key1", "value1"],["key2", "value2"],["key3", "value3"]]
OR
$json_array[] = array($key => $value); // Associative array
Output will be:
[{"key1": "value1"},{"key2": "value2"},{"key3": "value3"}]
Try:
sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$json_array[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
In your code you are parsing only the first db result
I have this json currently :
{"quest_id":"1","quest_title":"Buy 3 pints of draft and a large pizza and then get desert","quest_price":"15","quest_points":"100"}{"quest_id":"2","quest_title":"Hello WOrld","quest_price":"50","quest_points":"10"}
I was wondering how I could output this :
{"quests": {"quest_id":"1","quest_title":"Buy 3 pints of draft and a large pizza and then get desert","quest_price":"15","quest_points":"100"}{"quest_id":"2","quest_title":"Hello WOrld","quest_price":"50","quest_points":"10"}
}
Here is the code in php:
while($result=mysql_fetch_array($number, MYSQL_ASSOC)){
print(json_encode($result));
}
Try this:
$result = array('quests' => array());
while($row = mysql_fetch_array($number, MYSQL_ASSOC)){
$result['quests'][] = $row
}
echo json_encode($result);
If I understand correctly what you are trying to do, get a JSON packet with all the rows, then loop over them to put them in an array, then encode the whole array:
<?php
$result = mysql_query($query);
$out = array('quests' => array());
while ($row = mysql_fetch_assoc($result)) {
$out['quests'][] = $row;
}
print json_encode($out);
?>
I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the array so another function can display it. I need a way to display the returned assoc array. This should be a different function from the first one
print_r($array) will give nicely formatted (textually, not html) output.
If you just want information about what is in the array (for debugging purposes), you can use print_r($array) or var_dump($array), or var_export($array) to print it in PHP's array format.
If you want nicely formatted output, you might want to do something like:
<table border="1">
<?php
foreach($array as $name => $value) {
echo "<tr><th>".htmlspecialchars($name).
"</th><td>".htmlspecialchars($value)."</th></tr>";
}
?>
</table>
This will, as you might already see, print a nicely formatted table with the names in the left column and the values in the right column.
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $column => $value) {
//Column name is in $column, value in $value
//do displaying here
}
}
If this is a new program, consider using the mysqli extension instead.
Assuming you've made the call, and got $result back:
$array = new array();
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
return $array;
This should get you going:
$rows = mysql_query("select * from whatever");
if ($rows) {
while ($record = mysql_fetch_array($rows)) {
echo $record["column1"];
echo $record["column2"];
// or you could just var_dump($record); to see what came back...
}
}
The following should work:
$rows = mysql_query("select * from whatever");
if ($rows) {
$header = true;
while ($record = mysql_fetch_assoc($rows)) {
if ($header) {
echo '<tr>';
foreach (array_keys($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
$header = false;
}
echo '<tr>';
foreach (array_values($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
}
}
(Yes, blatant mod of Fosco's code)
This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.