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);
Related
I beginner to Amchart and am test load data in Amchart using php
this is my format json
[{"date":"2018-01-01","column-1":"5187"},{"date":"2018-01-02","column-1":"15790"},{"date":"2018-01-03","column-1":"15826"},{"date":"2018-01-04","column-1":"17026"},{"date":"2018-01-05","column-1":"17908"},{"date":"2018-01-01","column-2":"2143"},{"date":"2018-01-02","column-2":"6192"},{"date":"2018-01-03","column-2":"6106"},{"date":"2018-01-04","column-2":"6532"},{"date":"2018-01-05","column-2":"7000"}]
and this is my code
var data1 = <?php
include('connect.php');
$data = array();
$arr = array();
$query = "SELECT * FROM shell_table_graph";
$db = mysql_query($query);
while($rows = mysql_fetch_assoc($db)) {
$data[] = ['column' => $rows['column'], 'formula' => $rows['calculation']];
}
foreach($data as $rowss) {
$formula = $rowss['formula'];
$query = "SELECT Date, SUM(".$formula.") AS Formula FROM eod_split_interval WHERE Date BETWEEN '2018-01-01' AND '2018-01-05' GROUP BY Date";
$db = mysql_query($query);
while($r = mysql_fetch_assoc($db)) {
$arr[] = ['date' => $r['Date'], $rowss['column'] => $r['Formula']];
$code = json_encode($arr);
}
}
echo $code;
?>;
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);
}
}
I need to display categories and its sub categories in json format, here problem is each category has unlimited levels, some categories has 4 levels and some 2 and some 3 levels. I have tried one solution it is showing only one under level, but I need to show all levels.
Table schema:
Code Example:
function categories() {
header('Content-Type: application/json');
$sql = "select id,name,parent_id from categories where parent_id = 0";
$q = $this->db->conn_id->prepare($sql);
$q->execute();
$main_cat = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$sql2 = "select id,name,parent_id from categories where parent_id = ?";
$sub_cat = array();
$r = $this->db->conn_id->prepare($sql2);
$r->bindParam(1, $row['id']);
$r->execute();
while ($row1 = $r->fetch(PDO::FETCH_ASSOC)) {
array_push($sub_cat, array_filter($row1));
}
$row['subcategories'] = $sub_cat;
array_push($main_cat, array_filter($row));
}
echo json_encode(array("categories" => $main_cat));
}
Above Code Json Response Example:
{"categories":[{"id":"1","name":"Development","subcategories":[{"id":"2","name":"All Development","parent_id":"1"},{"id":"3","name":"Web Development","parent_id":"1"},{"id":"12","name":"Mobile Apps","parent_id":"1"}]},{"id":"4","name":"Design","subcategories":[{"id":"5","name":"All Design","parent_id":"4"}]},{"id":"11","name":"IT & Software"}]}
Any one can help me how to solve this issue.
I have tried this solution works for me.
function categories() {
$sql = "SELECT * FROM categories where parent_id = 0";
$results = $this->db->conn_id->prepare($sql);
$results->execute();
while ($result = $results->fetch(PDO::FETCH_ASSOC)) {
$subcat = array();
$id = $result['id'];
$childs = $this->hasChilds($id);
$categories[] = array("id" => $result['id'], "name" => $result['name'], "parent_id" => $result['parent_id'], "subcats" => array_filter($childs));
}
echo json_encode($categories);
}
function hasChilds($id) {
$sql = "SELECT * FROM categories where parent_id = ? ";
$results = $this->db->conn_id->prepare($sql);
$results->bindParam(1, $id);
$results->execute();
$count = $results->rowCount();
$array = array();
if ($count > 0) {
while ($result = $results->fetch(PDO::FETCH_ASSOC)) {
$array[] = array("id" => $result['id'], "name" => $result['name'], "parent_id" => $result['parent_id'], "subcats" => array_filter($this->hasChilds($result['id'])));
}
} else {
$array[] = null;
}
return $array;
}
I have an array that is populated by a mysql_fetch_assoc. After the array is populated by the columns I want from the database, I would like to add another key to the array, using values that I obtain earlier in the function. I tried to accomplish this with a foreach loop, but my function is not returning the array. Where have I gone wrong?
//calculates payout
function calculate_payout($id){
$result = mysql_query("SELECT `result` FROM `bets` WHERE `id` = {$id}");
echo mysql_error();
$wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `wager_total` FROM `wagers` WHERE `id` = '{$id}'");
$correct_wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `correct_wager_total` FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'");
echo mysql_error();
$incorrect_wager_total = $wager_total - $correct_wager_total;
$sql = " SELECT * FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'";
echo mysql_error();
$data = mysql_query($sql);
$rows = array();
while(($row = mysql_fetch_assoc($data)) !== false){
$rows[] = array(
'bet_id' => $row['bet_id'],
'id' => $row['id'],
'wager_amount' => $row['wager_amount']
);
}
foreach ($rows as $p_row){
$payout = $p_row['wager_amount'] / $incorrect_wager_total;
$payout = $p_row['wager_amount'] + $payout;
$p_row['payout'] = $payout;
}
return $p_row;
}
The problem is that $p_row is a copy of the row in the array, so modifying it in the loop doesn't have any effect on the original array.
You can fix this by using a reference in the foreach:
foreach ($rows as &$p_row)
Or you can just do this as you're creating the $rows array in the while loop:
while ($row = mysql_fetch_assoc($data)) {
$new_row = array(
'bet_id' => $row['id'],
'id' => $row['id'],
'wager_amount' => $row['wager_amount'],
'payout' => $row['wager_amount'] / $incorrect_wager_total + $row['wager_amount']
);
Also, your return statement is wrong, it should be return $rows; to return the whole array; return $p_row will just return the last row of the array.
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));