Convert/query array into JSON with PHP - php

I have a SELECT query that results in something like this:
USER_ID: 000030 USERNAME: Oprah RATING: 5
USER_ID: 000033 USERNAME: Pitbull RATING: 8
What I need is to display it in this form:
[[{"USER_ID":"000030","USERNAME":"Oprah","RATING":"5"},{"USER_ID":"000033","USERNAME":"Pitbull","RATING":"8"}]]
Generally I get this desired result with this SELECT:
try {
$stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
$stmt -> execute(array($userid));
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$output[] = $row;
}
}
print(json_encode($output));
But this time I had to get the result in this form:
try {
$stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
$stmt -> execute(array($userid));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$output[] = $row;
$row2[$i][$j] = $row['USER_ID'];
$j++;
$row2[$i][$j] = $row['USERNAME'];
$j++;
$row2[$i][$j] = $row['RATING'];
$i++;
$j=0;
}
}
How can I convert it into the desired form or form the query to produce it?
I tried these:
print(json_encode($row2));
[["000030","Oprah","5"],["000033","Pitbull","8"]]
$output[] = $row2;
print(json_encode($output));
[[["000030","Oprah","5"],["000033","Pitbull","8"]]]

For json_encode() to produce a json string that includes the associative indices, they need to be in the array you are encoding. If the indices are 0, 1, 2, etc., the indices will not show up in the json string.
Try this:
$i=0;
while(...) {
$row2[$i]['USER_ID'] = $row['USER_ID'];
$row2[$i]['USERNAME'] = $row['USERNAME'];
$row2[$i]['RATING'] = $row['RATING'];
$i++;
}
...
print_r(json_encode($row2));
Consider this PHP snippet for clarification.
Alternative methods of building array:
while(...) {
$row2[] = array(
'USER_ID' = $row['USER_ID'],
'USERNAME' = $row['USERNAME'],
'RATING' = $row['RATING']
);
}
// OR
$i=0;
while(...) {
foreach ($row as $key => $val) {
$row2[$i][$key] = $val;
}
$i++;
}

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output[] = array("USER_ID" => $row["USER_ID"],
"USERNAME" => $row["USERNAME"],
"RATING" => $row["RATING"],
);
}
print(json_encode($output));

Related

Datasource not available within second while loop

I have the following php code:
$user_id = $user["id_user_key"];
$stmt = $db->prepare("CALL spGetUserProducts(?)");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();
$data = array();
while($row = $result->fetch_assoc()) {
$row_array = array();
$row_array["id"] = $row["id"];
$row_array["pname"] = $row["pname"];
$row_array["picon"] = $row["picon"];
$row_array["menuItems"] = array();
$product = $row["id"];
//loop
$result_opt = $db->query("CALL spGetUserProductViews($user_id, $product)");
while ($opt_fet = $result_opt->fetch_assoc()) {
$row_array["menuItems"][] = array(
"id" => $opt_fet["id"],
"vname" => $opt_fet["vname"],
"isheader" => $opt_fet["isheader"]
);
}
array_push($data, $row_array);
}
$stmt->close();
echo json_encode($data);
The first loop can get a hold of $db, in other words: the first prepared statement is being excecuted and gives me results. The second one:
$result_opt = $db->query("CALL spGetUserProductViews($user_id, $product)");
gives me false. When I try this statement outside the loop, it does work.
Any thoughts ont his?
I found out that mysqli can't handle two simultaneous queries because mysqli uses unbuffered queries by default. Now, I could have dived into this (for example make use of $stmt->store-result()), but I also realized that I would like to keep the load on my database to a minimum.
My solution:
$data = array();
$user_id = $user["id_user_key"];
//menus -> products
$stmt = $db->prepare("CALL spGetUserProducts(?)");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$menus = array();
while($row = $result->fetch_assoc()) {
$menus[] = $row;
}
$stmt->close();
//items -> views
$stmt = $db->prepare("CALL spGetUserProductViews(?)");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$items = array();
while($row = $result->fetch_assoc()) {
$items[] = $row;
}
$stmt->close();
//generate object
//loop menus
foreach($menus as $m){
$row_array = array();
$row_array["id"] = $m["id"];
$row_array["pname"] = $m["pname"];
$row_array["picon"] = $m["picon"];
$row_array["menuItems"] = array();
//loop items
foreach($items as $i) {
if($m["id"] == $i["id_product"]) {
$row_array["menuItems"][] = array(
"id" => $i["id"],
"vname" => $i["vname"],
"isheader" => $i["isheader"]
);
}
}
array_push($data, $row_array);
}
echo json_encode($data);
So now I first generate arrays out of the two objects. then I do a foreach over the menus and then over the items. When the $menu["id"] equals $items["id_product"] then the array with items for that specific menu is being generated.
EDIT
After the data has been pulled from the database I first have to do a check wether or not the array contains data:
if(!empty($menus) && !empty($items)) {
foreach ($menus as $m) {
$row_array = array();
$row_array["id"] = $m["id"];
$row_array["pname"] = $m["pname"];
$row_array["picon"] = $m["picon"];
$row_array["menuItems"] = array();
//loop items
foreach ($items as $i) {
if ($m["id"] == $i["id_product"]) {
$row_array["menuItems"][] = array(
"id" => $i["id"],
"vname" => $i["vname"],
"isheader" => $i["isheader"]
);
}
}
array_push($data, $row_array);
}
}

Create a Multidimensional Array and json_encode

I have to get a JSON response from the database:
id and last_active:
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
while ($row = $stmt->fetch_assoc()) {
$users[]['id'] = $row['id'];
$users[]['last_active'] = $row['last_active'];
}
echo json_encode($users);
The array must be as follows:
$users = array (
0 => array(1, 1522921015),
1 => array(2, 1522921019),
2 => array(3, 1522921102),
3 => array(4, 1522921195),
4 => array(5, 1522921034)
);
How to properly build the multidimensional array with the query result?
Try this code
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
$i=0;
while ($row = $stmt->fetch_assoc()) {
$users[$i]['id'] = $row['id'];
$users[$i]['last_active'] = $row['last_active'];
$i++;
}
echo json_encode($users);
You can use temporary array like this:
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
while ($row = $stmt->fetch_assoc()) {
$tempArray = []; // added
$tempArray[] = $row['id'];
$tempArray[] = $row['last_active'];
$users[] = $tempArray; // added
}
echo json_encode($users);
or directly assign both values :
$users[] = array($row['id'],$row['last_active']);
Remove json_encode just print $user
You should push an array without keys to get the expected data:
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
while ($row = $stmt->fetch_assoc()) {
$users[] = [ $row['id'], $row['last_active'] ];
}
So, $users will be equals to:
$users = array (
0 => array(1, 1522921015),
1 => array(2, 1522921019),
2 => array(3, 1522921102),
3 => array(4, 1522921195),
4 => array(5, 1522921034)
);
Or, using the MYSQLI_NUM options with fetch_array():
while ($row = $stmt->fetch_array(MYSQLI_NUM)) {
$users[] = $row;
}
my choise will be like this:
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
while ($row = $stmt->fetch_assoc()) {
$users[] = [
$row['id'],
$row['last_active'],
];
}
echo json_encode($users);

Creating php json object array inside of array

I'm having trouble trying to figure out how would I create a Php json object that has an array inside of array. I have been working on this for hours and can't figure it out. Should I use oject inside my while loop and add array?
I Would like to have my answer array inside my question array like this.
{
"success":true,
"total":2,
"question":[
{
"id":"1",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"1",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
"question":[
{
"id":"2",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"0",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
See code below.
$question_arr = array();
$answer_arr = array();
//Question table results
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row_question_array['id'] = $row['ID'];
$row_question_array['product'] = $row['product'];
$row_question_array['question'] = $row['question'];
array_push($question_arr,$row_question_array);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$row_anwser_array['answer_id'] = $row2['answer_id'];
$row_anwser_array['product'] = $row2['product'];
$row_anwser_array['answer'] = $row2['answer'];
$row_anwser_array['is_correct'] = $row2['is_correct'];
$row_anwser_array['question_id'] = $row2['question_id'];
array_push($answer_arr,$row_anwser_array);
}
}
} else {
echo "question 0 results";
}
$myObj->success = true;
$myObj->total = $result->num_rows;
$myObj->question = $question_arr;
$myObj->answer = $answer_arr;
//echo json_encode($question_arr);
//echo json_encode($answer_arr);
echo json_encode($myObj);
There's no need to create two separate $question_arr or $answer_arr arrays. Instead, just create one empty result array $resultArr and refactor your code in the following way,
$resultArr = array();
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array('success' => true, 'total' => $result->num_rows);
while($row = $result->fetch_assoc()) {
$resultArr['question'][$row['ID']] = array('id' => $row['ID'], 'product' => $row['product'], 'question' => $row['question']);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['question'][$row['ID']]['answer'][] = $row2;
}
}
$resultArr['question'] = array_values($resultArr['question']);
} else {
$resultArr = array('success' => false, 'total' => 0);
echo "question 0 results";
}
echo json_encode($resultArr);

Why is this piece of code giving me duplicate results?

This is probably really easy and I'm probably gonna kick myself up the arse after this, but I have the following code which displays either html or json of data from a table and returns it.
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
}
?>
Now let's say for example, we want the json result, I'm getting the following string:
[{"id":1,"name":"My Tree","connections":4360}][{"id":1,"name":"My Tree","connections":4360},{"id":4,"name":"Another Tree","connections":0}]
Now for some reason, it's giving me the first result in one array, and then the same result, but with the other rows, in a separate array.
Fixed it, I knew it'd be silly:
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
}
//Moved echo outside of while loop.
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
?>

mySQL get data intro an associative array

I am using the below code to get the users list from my db:
if ($result = mysqli_query($mysqli, "SELECT user_name, name, surname, avatar, user_email FROM users")) {
while ($row = $result->fetch_assoc()) {
$username[] = $row["user_name"];
$user_email[] = $row["user_email"];
$user_name[] = $row["name"];
$user_surname[] = $row["surname"];
$avatar[] = $row["avatar"];
}
$result->close();
}
But I get the below error:
Fatal error: [] operator not supported for strings
This is probably what you want to do:
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// $rows is now an array that contains each individual row from your result set
You can then do whatever you want with that data, eg display it in a table or whatever.
foreach($rows as $user)
{
echo $user['user_name'] . ' - ' . $user['user_email'];
}
And so on
Your $username variable has been set as a string somewhere in the code before the codeblock you have posted. If you use $username=array(); you will loose that variable. I don't know if you need it or not.
Here is a better way to do :
$users = array();
while ($row = $result->fetch_assoc()) {
$users[] = array(
"username" => $row["user_name"],
"email" => $row["user_email"],
"name" => $row["name"],
"surname" => $row["surname"],
"avatar" => $row["avatar"]
);
}
And you can loop the users using foreach:
foreach($users as $user){
echo $user["username"];
echo $user["email"];
}
you should take an empty array befor loop if you want these into array. like this
if ($result = mysqli_query($mysqli, "SELECT user_name, name, surname, avatar, user_email FROM users")) {
$results=array();
while ($row = $result->fetch_assoc()) {
$results []=$row;
}
$result->close();
}
other wise you should remove []
You can do this also -
$user_data = array();
while ($row = $result->fetch_assoc()) {
$user_data[] = $row;
}
By this you can get all the data in a single array. The keys will be the same as database fields.

Categories