Fetching data from mysql table and placing values inside a JSONObject - php

I am fetching values from mysql table. I am then placing the values inside an array and using th php built function json_enconde to convert these values into a json format. I am getting results back but not in the desired format. In the php code you will notice I am using array and fetching values with a foreach loop to place all values inside. As a result I am getting back several json objects. How can I get back just one json object with the corresponding values?
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[] = array(
$row["id"] => $row["name"]
);
} // foreach ($data as $row) {
echo json_encode($json_data);
Results:
{
1: "Item1"
},
{
2: "Item2"
},
{
3: "Item3"
}
Desired Results:
{
"1":"Item1",
"2":"Item2",
"3":"Item3"
}

change this array( $row["id"] => $row["name"]);
to $json_data[$row["id"] ] = $row["name"] inside the for loop
foreach ($data as $row) {
$json_data[$row["id"] ] = $row["name"];
}

try this
foreach ($data as $row) {
$id=$row["id"];
$json_data[$id] =$row["name"];
}
The problem was that while defining the value in json_data in your foreach loop you are creating an array for every single value, so you are not getting the desired result.

You will need to change your PHP code to create a normal single dimensional array, right now you are creating a multidimensional array. Your PHP should be like this:
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[$row["id"]] = $row["name"];
} // foreach ($data as $row) {
echo json_encode($json_data);
Notice the change in the foreach loop, we are no longer appending a new array onto the $json_data array(which would create a multidimensional array). This will give you a single dimensional array with the proper key:value pairs. Then when you run the json_encode you will get your desired JSON format.

Related

how to convert jquery post values to array

post values from jquery are (id_workers: 1124,1545,4268)
$rows= array($_POST['id_workers']);
foreach($rows as $row) {
echo $row;// has to echo 112415454268
but its show 1124,1545,4268
}
// sample code workers perfectly
$rows= array(1124,1545,4268);
foreach($rows as $row) {
echo $row;// result 112415454268
}
unable to figure out the issue.
You are getting 1124,1545,4268 because $_POST['id_workers'] having string value comma separated like "1124,1545,4268".
When you try to use array("1124,1545,4268") it will use only 1 index like:
Array ( [0] => 1124,1545,4268 )
So, you need to use explode() here to convert string into an array like:
$rows= explode(",",$_POST['id_workers']);
foreach($rows as $row) {
echo $row; // 112415454268
}
If comma is an issue only, you can also use str_replace() to remove comma from a string like:
$rows = $_POST['id_workers'];
echo str_replace(",", "", $rows); // 112415454268

When I try to access to array items I only get the 1. one

Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.

PHP storing a two dimension array from MySQL query

I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.
I am able to store a one dimension array like the following:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row['name'];
}
How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?
Simply do this:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
To access your results you can do this:
$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];
This will tell you if a particular row exists:
if(isset($array[$x])) {
$aRow = $row[$x];
// do stuff with $aRow;
}
This will give you a row count for your array:
$rowCount = count($array);
This will set up a loop through your array:
foreach($array as $index => $row) {
$id = $row['id']
$name = $row['name'];
// $index will have the array index of the current row. 0 -> $rowCount - 1
}
Don't specifically store the index of $row but rather store the whole row.
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
Then $array will have the following structure:
$array = [
[
'id'=> ...,
'name' => ...,
],
...
];
To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL. This will signal to your while loop to stop iterating.
Then to access variables inside of your $array, I recommend using foreach.
You could then do:
foreach ($array as $row) {
do something with $row['name'] or $row['id']
}
You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:
for ($i = 0; $i < count($array); $i++) {
$row = $array[$i];
do something with $row['name'] or $row['id']
}

Array push rows from SQL query

I am trying to save the rows (results) from an SQL query to a csv file.
I am using array push in order to put the results in a list. Later I put the data from this list to my csv file.
My code :
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list, $row['campaign']);
}
The results are there because sprintf works. The problem is with the syntax of array_push. I even tried :
array_push($list, array(''.$row['campaign']);
I am getting an error:
fputcsv() expects parameter 2 to be array
The full code is here :
$list = array
(
array('old_campaign_name', 'new_campaign_name')
);
// table 1
$sql = ('select distinct(campaign) as campaign from '.$table1.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list,$row['campaign'],'');
}
$fp = fopen($location, 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
As the error says, fputcsv expects each row that you put to be an array, so it can write it out with commas separating the elements. $list should be a 2-dimensional array, so you need to push an array onto it when you're building it.
while ($row = $query->fetch_assoc() {
$list[] = array($row['campaign']);
}
BTW, $list[] = x is equivalent to array_push($list, x).
When you initially create the $list array, it is an array containing one array. But when you add more values to it from your query results, you are pushing strings onto the end of it, not arrays. In effect, you will be making something like
$list = array (
array('old_campaign_name', 'new_campaign_name'),
'first campaign',
'second campaign',
'etc.',
...
);
Because of this, when you loop over $list, the first value should work with fputcsv, because it is an array, but any subsequent values will be strings instead of arrays and will cause the error you are seeing.
You should be able to fill the $list like this:
while ($row = $query->fetch_assoc()) {
$list[] = $row;
}
$list[] = $row will not overwrite the values previously in $list. From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
It works like this :
while ($row = $query->fetch_assoc())
{
// array_push($list,$row['campaign'],'');
array_push($list,array($row['campaign'], ''));
}

Formatting values inside json object - json_encode()

I have a foreach loop that fetches values from mysql table. After fetching the values, their placed inside an array and then finally converted into a json object. The format of the json object has to be specific in order to work properly with third party api that I am currently using. The results I am getting currently placed all the values inside a json object. My goal is to pair values on separate json objects {},{},etc. In addition, How can I add labels inside the object for the values that were fetch?
$level_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt
FROM academy a
GROUP BY a.type");
$level_query->execute();
$data = $level_query->fetchAll();
$level_data = array();
foreach ($data as $row) {
$type = $row["type"];
$level_data[$type] = $row["cnt"];
} // foreach ($data as $row) {
echo json_encode($level_data);
Current Format:
{" Expert":"12","Intermediate":"512","Beginner":”1002”}
Correct/Desired format Format:
{ level: "Expert", count: 12 },
{ level: "Intermediate", count: 512 },
{ level: "Beginner", count: 1002 }
Try this:
$output = array();
foreach ($data as $row) {
array_push($output, array('level'=>$row["type"], 'count'=>$row["cnt"]));
}
echo json_encode($output);
The desired format looks like a array of objects, each of which contains a level and a count property.
Data like this:
$data = array(
array('type'=>'a','cnt'=>1),
array('type'=>'b','cnt'=>2),
array('type'=>'c','cnt'=>3),
array('type'=>'d','cnt'=>4),
array('type'=>'e','cnt'=>5)
);
Comes out like this:
[{"level":"a","count":1},{"level":"b","count":2},{"level":"c","count":3},{"level":"d","count":4},{"level":"e","count":5}]

Categories