How to decode a row from mysql database and encode it - php

I am trying to JSON decode row Options and encode it with rest of data. But it is only giving me Options row but. If I don't decode it give me this with backslashes in Options row.
[{"ID":"4","AppID":"1","Question":"test2","Type":"Radios","OrderNumber":"2","Options":"{\"Number1\":
\"Yes\", \"Number2\": \"No\"}"}]
//open connection to mysql db
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbdata) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from App_Questions";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while ($row =mysqli_fetch_assoc($result)) {
if ($row["Options"]){
$str = json_decode($row["Options"]);
$emparray = $str;
}else{
$emparray[] = $row;
}
}
echo json_encode($emparray);

Assuming you want to decode the field "Options" which has json data saved to it, and then you want to encode those json data with rest of the other fields. The json decoded output is this from our question:
array (
0 =>
array (
'ID' => '4',
'AppID' => '1',
'Question' => 'test2',
'Type' => 'Radios',
'OrderNumber' => '2',
'Options' => '{"Number1": "Yes", "Number2": "No"}',
),
)
If you decode "Options", you get this:
array (
'Number1' => 'Yes',
'Number2' => 'No',
)
You can do something like this to encode this with rest of the data inside the loop:
$decodedData = json_decode($results);
foreach ($decodedData as $row) {
if (isset($row->Options)) {
$decodedOptions = json_decode($row->Options);
foreach ($decodedOptions as $key => $value) {
$row->$key = $value;
}
}
}
$decodedData = json_encode($decodedData);
print_r($decodedData);

Related

php datatable array results

I am trying to extract data from mysql database into a datatable using ajax, and php.
The code for my response.php file is below:
<?php
$result = mysql_query("select * from orders");
while ($row = mysql_fetch_array($result)) {
$data = array(
array(
'Name' => $row['jobnumber'],
'Empid' => $row['ID'],
'Salary' => $row['product']
)
);
}
$results = array(
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
);
/*while($row = $result->fetch_array(MYSQLI_ASSOC)){
$results["data"][] = $row ;
}*/
echo json_encode($results);
?>
Why is this only returning one result in my front end table?
http://orca.awaluminium.com/test.php
link above shows table.
You're replacing value of $data instead of pushing new rows in an array.
Change the following line.
$data = array(
array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
)
);
To
$data[] = array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
);
Also put $data=array(); before string while() looop.
You have to do foreach
while ($row = mysql_fetch_array($result)){
foreach($row as $a)
{$data[] = array(
array('Name'=>$a['jobnumber'], 'Empid'=>$a['ID'], 'Salary'=>$a['product']),
);
}
}

Store array into array of array

Im generating Chart4PHP.
In sample it takes data like this
$p->data = array(array(array("2010/10",-48),array("2011/01",238),array("2011/02",395)));
I have array "rows" constructed of row[date][units].
Im storing it in this way:
$rows = array();
for(...)
{
$row[date] = $mydate;
$row[units]= $myunits;
$rows[]=$row;
}
What I should make additionally to be able to use it as $p->data = $rows;
To add the extra array container, call array() with the rows array as the argument.
$data = array(array('date' => "2010/10", 'units' => -48),
array('date' => "2011/01", 'units' => 238),
array('date' => "2011/02", 'units' => 395));
foreach ($data as $d) {
$mydate = $d['date'];
$myunits = $d['units'];
$rows[] = array($mydate, $myunits);
}
$p->data = array($rows);

Extracting data from a database into array

I'm building an angular application, so I have a PHP script extracting the database data into a JSON when requested.
This is what I'm using to extract the data into an array:
$values = array();
$query = "SELECT * FROM photos ORDER BY id";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
array_push($values, $row);
}
json_encode($values);
But it gives no result.
After some testing, if I change json_encode($values); to print_r($values); it actually print the table array, here an extract:
Array (
[0] => Array (
[id] => 4
[title] => Feel the Moment
[views] => 6
)
It seems the script is not creating a valid array.
$query = "SELECT * FROM photos ORDER BY id";
if ($result = $this->mysqli->query($query)) {
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = $row;
}
echo json_encode($json);
}
Your while is not executing, probably because you don't have any returned values from database.
I tested this code and it works well:
$json = array();
$json[] = array(
"id" => 1,
"category" => 'a',
"tags" => 't');
$json[] = array(
"id" => 2,
"category" => 'b',
"tags" => 'tt');
echo json_encode($json);
The result is:
[{"id":1,"category":"a","tags":"t"},{"id":2,"category":"b","tags":"tt"}]
And you'd better use mysqli_fetch_row or mysqli_fetch_assoc.
Try to debug your code. You may use var_dump($result->fetch_assoc()) to see if the query has some results.

Displaying multiple rows in PHP array

I have a script I wrote to return records for cases out of the database. I am returning one record for my mysql query when there are actually two records. This is what I am returning:
{ "cases": [ {"name":"Test Case for App","number":"3846"}] }
I should see:
{ "cases": [ {"name":"Test Case for App","number": "2903"}, {"name":"Test Case 2","number": "2856"} ] }
Here is my source:
$sql = "select * from cases as c join contacts_cases as conc on c.id = conc.case_id where conc.contact_id = '1b360507'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_assoc($query);
$response = array(
'name' => $row['name'],
'number' => $row['case_number']
);
echo '{ "cases": [ ', json_encode($response), "] }";
If you are expecting more than one result you should try
if (mysql_num_rows($query) > 0)
{
$responses = array();
while($row = mysql_fetch_assoc($query)) {
$responses[] = array(
'name' => $row['name'],
'number' => $row['case_number']
);
}
echo '{"cases": ' . json_encode($responses) . '}';
}
You need to loop through all the rows, you're just getting one.
Also, don't try to build the JSON yourself. Make the array how you want then json_encode the entire thing.
$cases = array();
while ($row = mysql_fetch_assoc($query)) {
$cases[] = array(
'name' => $row['name'],
'number' => $row['case_number']
);
}
echo json_encode(array('cases' => $cases));

Ouput data in JSON format on Array in PHP

$result = mysql_query($query);
$leaderboard = array();
while($row = mysql_fetch_assoc($result)) {
$leaderboard[$row["username"]] = $row["score"];
}
$output = array
(
'status' => 1,
'content' =>$leaderboard
);
print_r(json_encode($output));
right now the $output array is such JSON:
{"tim":"120","john":"45","larry":"56"}
but I want to have them as key-value pair so instead I want to be like:
{"name":"tim","score":120","name":"john","score="45", etc.}
and if I need that way, how do I modify the $leaderboard array so the output would be like that?
$leaderboard[] = Array('name' => $row["username"], 'score' => $row["score"]);

Categories