PHP MySQLi select from database and push to json - php

$q = $db->query("SELECT * FROM user");
while($row = mysqli_fetch_array($q)) {
$product = array();
$product['id'] = $row['id'];
$product['user'] = $row['user'];
$product['data'] = $row['data'];
}
$response["product"] = array();
array_push($response["product"], $product);
I have been trying to select from a database the entire table and then loop through each result and push it to an array. The above code only seems to put to the array the last item in the table.

You're probably better off doing something like this:
$q = $db->query("SELECT * FROM user");
$response = array();
$response["product"] = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'id' => $row['id'],
'user' => $row['user'],
'data' => $row['data'],
);
array_push($response["product"], $product);
}
You were only getting the last item because you kept resetting your $response['product'] & $product array.

You need to push into the array for each item. At the moment you overwrite $product each time though the loop. Try this:
$q = $db->query("SELECT * FROM user");
$response["product"] = array();
while($row = mysqli_fetch_array($q)) {
$product = array();
$product['id'] = $row['id'];
$product['user'] = $row['user'];
$product['data'] = $row['data'];
array_push($response["product"], $product);
}

Related

array_push in PHP seems to get into infinite loop

I am new to PHP. I am trying to read MySQL with this PHP code.
....
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = array();
$return = array();
while($row = mysqli_fetch_array($result)) {
$rows['UserId'] = $row['UserId'];
$rows['Nick'] = $row['Nick'];
$rows['Items'] = $row['Items'];
$rows['Skills'] = $row['Skills'];
...
$rows['LastUpdate'] = $row['LastUpdate'];
array_push($return, $rows);
}
header("Content-type:application/json");
echo json_encode($return);
Soon after runnning this code, it gets into infinite loop.
When I deleted the array_push line, it did not go into infinite loop.
So I guess that'd be the problem, but I can't find out why.
Is there something wrong with my code?
The MySQL database is in Amazon lightsail.
Please help me. Thanks in advance for any comments.
if you want to fetch all rows from database, and get data array of specific fields
<?php
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$filtered = [];
while($row = mysqli_fetch_all($result)) {
$filtered[] = [
'UserId' => $row['UserId'],
'Nick' => $row['Nick'],
'Items' => $row['Items'],
'Items' => $row['Items'],
'Skills' => $row['Skills'],
'Items' => $row['Items'],
'LastUpdate' => $row['LastUpdate'],
];
}
header("Content-type:application/json");
echo json_encode($filtered);
foreach record of your database information you are entering new data to rows array
while($row = mysqli_fetch_array($result)) {
// Logic of you application here
array_push($return, $row);
}
this pushes fetched row into rows array
how ever if you are not modifying database fetched information. you can fetch information as associative array and simply store it in variable. there will be no need for loop and storing in new array
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
header("Content-type:application/json");
echo json_encode($rows);

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);
}
}

How do I hide arrays php with an empty value of 0?

I have to hide all empty arrays from the result or with value = 0. How can I do?
$return_arr = array();
$fetch = mysqli_query($conn, "SELECT...");
while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
$row_array['id'] = $row['ordr'];
$row_array['name'] = $row['name'];
$row_array['icon'] = $row['icon'];
$row_array['file_a'] = $row['file_a'];
$row_array['file_b'] = $row['file_b'];
$row_array['file_c'] = $row['file_c'];
$row_array['file_r'] = $row['file_r'];
array_push($return_arr,$row_array);
}
$response_arr = json_encode($return_arr);
return $response_arr;
}
There is missing code from your function so I have worked with what is available.
Try selecting only the cols you want data from and then check if col is empty per row. If there is a column that has data then the whole row is returned.
$return_arr = array();
$fetch = mysqli_query($conn, "SELECT name,icon,file_a,file_b,file_c,file_r FROM...");
while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
$tmp = 0;
foreach( $row as $key => $val ){
if( !empty($row[$key]) ) $tmp++;
}
if( $tmp > 0 ) array_push($return_arr,$row_array);
}
$response_arr = json_encode($return_arr);
return $response_arr;
}
Also array_filter might be helpful as it can exclude all false values on the results set (used without callback).
More info on array_filter

Printing multiple table queries using json_encode in php

I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
echo json_encode($data);
?>
I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:
<?php
include('db.php');
$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
echo json_encode($data_pro);
?>
How can I accomplish this?
I think this might hit what you're looking for.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;
echo json_encode($all_data);

PHP JSON Array not returning all rows from my database

$retrieve = mysql_query("SELECT * FROM `users`") or die(mysql_error());
$object -> userDetails = array();
while($retrieveArray = mysql_fetch_array($retrieve))
{
$item -> userId = $retrieveArray['id'];
$item -> userEmail = $retrieveArray['email'];
$item -> userLocation = $retrieveArray['location'];
$item -> userFirstName = $retrieveArray['firstname'];
$item -> userLastName = $retrieveArray['lastname'];
$object ->userDetails[] = $item;
}
$json = json_encode($object);
echo $json;
Is there something wrong with this code? My output only displays the first row of my database.
{"userDetails":[{"userId":"1","userEmail":"EmailAddress#gmail.com","userLocation":"HomeAddress","userFirstName":"Allan","userLastName":"Knocks"}]}
Try this:
$retrieve = mysql_query("SELECT id, email, location, firstname, lastname FROM `users`") or die(mysql_error());
$userDetails= array();
while($row = mysql_fetch_assoc($retrieve)) {
$userDetails[] = $row;
}
$json = json_encode(array('userDetails' => $userDetails));
echo $json;
Beware! Doing this in a loop will modify the same instance many times and you will end up with the same object added many times to your array:
while($retrieveArray = mysql_fetch_array($retrieve))
{
$item -> userId = $retrieveArray['id'];
$item -> userEmail = $retrieveArray['email'];
$item -> userLocation = $retrieveArray['location'];
$item -> userFirstName = $retrieveArray['firstname'];
$item -> userLastName = $retrieveArray['lastname'];
//you are adding here the same object with changed properties.
$object ->userDetails[] = $item;
}
In the end $object->userDetails will contain n references to the same object with the last set properties.
Instead you should create a new instance inside the loop :
while($retrieveArray = mysql_fetch_array($retrieve))
{
//new item (if there is a class Item)
$item = new Item();
// if $item is just a stdObject created on the fly then use
$item = new stdClass();
$item -> userId = $retrieveArray['id'];
$item -> userEmail = $retrieveArray['email'];
$item -> userLocation = $retrieveArray['location'];
$item -> userFirstName = $retrieveArray['firstname'];
$item -> userLastName = $retrieveArray['lastname'];
//you are adding here another object
$object ->userDetails[] = $item;
}
You can try
$sql = "SELECT * FROM users";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$userDetails = array();
while ($row = $result->fetch_assoc()) {
$userData[] = array(
"id" => $row["id"],
"name" => $row["name"],
"email" => $row["email"],
);
}
} else {
echo "0 results";
}
$result1['regular'] = $userData;
$json = json_encode($result1);
echo $json;
Your json will look like bellow
{"regular":[{"id":"2","name":"enamul Haque","email":"ehaque95#gmail.com"},{"id":"55","name":"Rafiq","email":"era#gmail.com"}]}

Categories