display mutidimentional array result as table - php

I will like to display the result of my multidimensional array in a table like this
Thank you for any help.
| product ID | Product Name | Quantity | Price
--------------------------------------------------------------------
|$item['part_id']| $product_name| $item['quantity']| $item['price']
--------------------------------------------------------------------
|$item['part_id']| $product_name| $item['quantity']| $item['price']
......
here is the result of my array
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Number of item selected: ' . mysqli_affected_rows($con)."<br/>";
foreach($_SESSION["cart_array"]as $item){
$i++;
$item_id=$item['part_id'];
$sql = mysqli_query($con,"SELECT * FROM oproduct_description
WHERE product_id='$item_id' LIMIT 1");
While($row=mysqli_fetch_array($sql)){
$product_name=$row["name"];
}
echo'itemID '.$item['part_id']."";
echo'product name '.$product_name."";
echo 'item Quantity '.$item['quantity']."";
echo 'item Price '.$item['price']."<br/>";
}
}

Well instead of echoing out I would create a table array and use a function call to output the table.
$arrayVariable[] = array(
'itemID' => $item['part_id'],
'productName' => $product_name,
'itemQuantity' => $item['quantity'],
'itemPrice' => $item['price']);
function tableFunction($a){
echo '<table><tr>| product ID | Product Name | Quantity | Price</tr>';
foreach($a as $rowData){
echo "<tr>|$rowData['itemID']| $rowData['productName']| $rowData['itemQuantity']| $rowData['itemPrice']</tr>";
}
echo '</table>';
}

Related

Remove Duplicates in while loop PHP

I'm trying to remove duplicate results from my SQL query using PHP.
table categories:
id | name
1 | sony
2 | nintendo
table subcategories:
id | name | category_id
1 | playstation | 1
2 | playstation2 | 1
3 | wii | 2
table video_games
id | name | subcategories
1 | grand theft auto | 1,2
2 | super mario | 3
My PHP code:
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
echo $game_return['name'];
}
}
}
My code works but I have duplicate video games when there have multi subcategories.
I tried using SELECT DISTINCT * FROM video_games WHERE subcategories LIKE :request but same problem.
Any idea to remove duplicate results using SQL or PHP ?
MySql is able to solve this problem by its own means.
Use 'DISTINCT' and 'FIND_IN_SET'.
Like this:
"SELECT DISTINCT
vg.id,
vg.name,
vg.subcategories
FROM
video_games vg
WHERE
FIND_IN_SET( (SELECT id FROM subcategories WHERE category_id='".$_GET['id'])."' , vg.subcategories ) > 0 "
and also you can use array_unique at first save video game names in an array and next remove duplicate value.
.
.
.
your code
.
.
$game_query->execute();
if($game_query->rowCount() > 0) {
$fetch =array_unique($game_query->fetch());
foreach ($fetch as $key => $value){
echo $value;
}
}
test
<pre>
<?php
$arr=array("name"=>"1","name2"=>"2","name1"=>"2","name3"=>"3","name4"=>"1","name5"=>"2","name6"=>"3","name7"=>"22");
print_r($arr);
$fetch =array_unique($arr);
print_r($fetch);
foreach ($fetch as $key => $value)
echo $key."=>".$value."<br>";
?>
</pre>
You can save video game names in an array, and print it afterwards. For example:
$games = array();
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
if (!in_array($game_return['name'], $games)) {
$games[] = $game_return['name'];
}
}
}
}
//now print the games
foreach ($games as $game) {
echo $game;
}
EDIT If you want more than just 'name', you can expand $games array with $key => $value combination. For example:
. . .
while($game_return = $game_query->fetch()) {
foreach ($games as $game) {
if ($game['name'] === $game_return['name']]) {
continue 2;
}
}
$games[] = array(
'name' => $game_return['name'],
'price' => $game_return['price'],
)
}
And afterwards print it like:
foreach ($games as $game) {
echo $game['name'];
echo $game['price'];
}

echo item according to session result quantity

I want to fetch and echo item from MySQL database multi-times according to session quantity.
Example :
id | qty | item
1 | 2 | shoe
2 | 4 | net
3 | 3 | phone
My result set should be like this :
shoe, shoe
net, net, net, net
phone, phone, phone
I tried :
if(isset($_SESSION["cart_products"]))
foreach ($_SESSION["cart_products"] as $each_item){
$item_id = $each_item['item_id'];
$qty = $each_item['quantity'];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' ORDER BY id");
$qty = array();
while ($row = mysql_fetch_array($sql)) {
$qty[] = $row;
}foreach($qty as $row){
$product_name = $row["product_name"];
}
echo'$product_name';
Any help is appreciated.
if(isset($_SESSION["cart_products"]))
foreach ($_SESSION["cart_products"] as $each_item){
$item_id = $each_item['item_id'];
$qty = $each_item['quantity'];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id'
ORDER BY id");
while ($row = mysql_fetch_array($sql)) {
$qty = $row['qty'];
for($i=0; $i < $qty; $i++){
echo $row['item'].' ';
}//end for
echo '<br>';//go to next-line
}//end while
}//end foreach

How do I list all the products in the sub-categories for the top categories

My database category and product are:
Category Table : id,name,parent_id
Product Table : id,name,category_id
My Category menu is:
-Category A
--Category A1
--Category A2
---Category A2a etc..
Each product has only one category related:
Product1 -> Category A1
Product2 -> Category A2
Product3 -> Category A2a etc..
The code of all of the product category and subcategory
category.php?category_id=1 (exp. category A)
<?php
function FetchAllRows($sql) {
global $db;
$stmt=$db->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
function getCategoryChild($children) {
$sql = "SELECT * FROM `category` WHERE `parent_id` = $children";
$rows = FetchAllRows($sql);
$sub_category_id = array();
foreach($rows as $row) {
// $sub_category_id[$row['id']] = getCategoryChild($row['id']);
$cat = getCategoryChild($row['id']);
$sub_category_id[] = array(
'children' => $cat,
'category_id' => $row['id']
);
}
return $sub_category_id;
}
$a = getCategoryChild($category_id);
echo $in = join(',', array_fill(0, count($a), '?'));
$query="SELECT * FROM product WHERE category_id IN ($in)";
I tried this latest application. We did not get results. My English is not good. Hopefully presence. Until the array elements in I want to transfer into SQL.
I solved the problem.
I delete these two lines.
echo $in = join(',', array_fill(0, count($a), '?'));
$query="SELECT * FROM product WHERE category_id IN ($in)";
I invested only category_id 's.
foreach($a as $index => $b) {
$subs[$index] = $b['category_id'];
}
$ids = implode($subs,',');
$query = $db->query("SELECT * FROM `product` WHERE category_id IN($ids);");

How to create a JSON from table PHP

How to create a json like this in php;
[{"idorder":"34",
"totalOrder":"55",
"products":[{"idproduct":"5","price":"10"},{"idproduct":"4","price":"45"}]
}]
from table mysql;
+---------+-----------+--------------+
| idorder | idproduct | priceproduct |
+---------+-----------+--------------+
| 1 | 4 | 45 |
| 1 | 5 | 10 |
+---------+-----------+--------------+
my current code something.php;
...
$result = $conn->query($pendientesq);
$return_arr = array();
$productos = array();
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
//But now????How to create sub array with multiples products.
echo json_encode($return_arr);
you need to try something like this:
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
// suposse total products are 10
$product=10;
for($i=0;$i<product;$i++){
$return_arr['product'][] = array("idproduct"=>$i,"price"=>$i);//use your price and idproduct.
}
echo json_encode($return_arr);
I don't know how Your table looks like because You've not described it.
But I got for example "orders" table with idorder,idproduct,priceproduct fields.
And wrote this code:
// $q = "SELECT * FROM orders WHERE idorder = 5"; // for single order
$q = "SELECT * FROM orders";
$result = $conn->query($q);
$orders = [];
while($record=$result->fetch_array()) {
if(!isset($orders[$record['idorder']])) {
$orders[$record['idorder']] = [];
$orders[$record['idorder']]['idorder'] = $record['idorder'];
$orders[$record['idorder']]['totalOrder'] = 0;
$orders[$record['idorder']]['products'] = [];
}
$orders[$record['idorder']]['products'][] = ['idproduct' => $recrod['idproduct'],
'price' => $record['priceproduct']];
$orders[$record['idorder']]['totalOrder'] += $record['priceproduct'];
}
$orders = array_values($orders);
echo json_encode($orders);

Sort items by category

I have a table containing the following records:
product_id | title | category
------------------------------------
1 | apple | mobile
2 | android | mobile
3 | dell | desktop
4 | hp | desktop
and the following query:
$sql = "SELECT product_id, title, category FROM products ORDER BY category";
$stmt = $db->prepare($sql);
$stmt->execute();
while($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $results["product_id"];
echo $results["title"];
echo $results["category"];
}
The question is how to split the results and display all records in a list sorted by category as below:
Mobile
Apple
Android
Desktop
Dell
HP
Group your records after get the result set:
$products = array();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$products[$results['category']][] = array(
'product_id' => $results['product_id'],
'title' => $results['title']
);
}
foreach ($products as $category => $productList)
{
echo $category . '<br>';
foreach ($productList as $product)
{
echo $product['title'] . '<br>';
}
echo '<hr />';
}
Use SELECT * FROM products GROUP BY category ORDER BY title
After sorting your items (ORDER BY category, title), do something like this:
$last_category = "";
while(/* get a row here */) {
if( $last_category != $row['category']) {
if( $last_category != "") echo "</ul>";
echo "<ul>";
$last_category = $row['category'];
}
echo "<li>".$row['title']."<li>";
}
if( $last_category != "") echo "</ul>";
SELECT * FROM products ORDER BY category. This is to sort using category, your example output file seems different what are you trying to do?

Categories