I am trying to sum up the value. I have stored in the database price and qty. The total = price * qty for that particular item.
I would like to sum all of the items for a sub total.
$sql = "SELECT * FROM parts WHERE jobno = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$results['entrants'][] = array(
'partno' => $row['partno'],
'description' => $row['description'],
'price' => $row['price'],
'qty' => $row['qty'],
'total' => $row['price'] * $row['qty'],
);
}
} else {
// Create an empty placeholder record if no entrants were found
$results['entrants'][] = array(
'partno' => NULL,
'description' => NULL,
'price' => NULL,
'qty' => NULL,
'total' => NULL,
);
}
I only know SELECT sum - which I don't think will work because I am not getting the information from the database but from the above.
Just keep track as you go:
$subTotal = 0;
while ($row = $result->fetch_assoc()) {
$lineTotal = $row['price'] * $row['qty'];
$subTotal += $lineTotal;
$results['entrants'][] = array(
//...
'total' => $lineTotal;
);
}
$results['subtotal'] = $subTotal;
Related
I want to create json which contains all orders from datebase. I tried to write this code but it returns only one order.
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders =[
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
Now the response looks like this:
But I want like this:
Append to the $orders array:
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders[] =[ // <--- The difference
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
Ok so I have two tables Category and Dishes. Each Category has an id. And each dish belongs to a particular category. Now what I want is for all dishes belonging to a particular category to be grouped together. So All the Soups will be in the Soups Array [{Cabbage,Price,Description,...}, {Tomato,Price,Description,...}]. All the chicken in the chickens array and so forth. What I'm Currently doing is this:
$query = "Select id from Category";
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row["id"];
}
foreach ($idlist as $id){
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
But this results in all the dishes being grouped together. How do I separate the dishes based on their category? Also is this the right way to structure JSON Data?
1.Use JOIN to do that in single query (best solution):-
$query = "Select Dishes.*,Category.id as cat_id from Category LEFT JOIN Dishes on Dishes.cat_id = Category.id";
$Listings = $mysqli->query($query);
$AllDishes = array();
while($row = $Listings->fetch_assoc()) {
$AllDishes[$row['cat_id']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
print_r($AllDishes);
If you want to do in your coding way then:-
2.Distinguish them based on id of the category:-
$query = "Select id from Category";//change column name
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row['id'];
}
foreach ($idlist as $id){
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[$id][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
3.Distinguish them based on name of the category:-
$query = "Select id,category_name from Category";//change column name
$Id = $mysqli->query($query);
while($row = $Id->fetch_assoc()) {
$idlist[] = $row;
}
foreach ($idlist as $id){
$id = $id['id'];
$category_name = $id['category_name']; //change column-name
$query = "SELECT * from Dishes where Dishes.cat_id = '$id'";
$Listings = $mysqli->query($query);
while($row = $Listings->fetch_assoc()) {
$AllDishes[$category_name][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
}
Note:- Please change the column-name in 3rd solution(as i don't know what column-name you have to store category names.)
I am not sure but i thinks here will be your while loop for expected results
$AllDishes = array();
while($row = $Listings->fetch_assoc()) {
$AllDishes[$row['Name']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'cat_id' => $row['cat_id'],
'Price' => $row['Price'],
'ImagePath' => $row ['ImagePath']
);
}
You can use SQL joins instead of two separate SQL queries
I hope the following may help you.
$query = "SELECT * FROM Dishes INNER JOIN Category
ON Dishes.id = Category.id ORDER BY Dishes.id";
$res = $mysqli->query($query);
while($row = $res->fetch_assoc())
{
$AllDishes[$$row['category_name']][] = array(
'id' => $row['id'],
'Name' => $row['Name'],
'Description' =>
$row['Description'],
'cat_id' =>
$row['cat_id'],
'Price' => $row['Price'],
'ImagePath' =>
$row['ImagePath']
);//Array Close
}
if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
$productID = $_REQUEST['id'];
// get product details
$sql = "SELECT * FROM products WHERE id = ".$productID;
$stmt = $db->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
I am trying to get the the prod name, qty and price - to be placed on viewCart.php. I am new please help me with this.
now i am having a hard time in placing all my values in an associative array.
Because I can only get the last value from query. Not all the values. I can't spot the error.
Here's my code:
$sqlGetSerializedValues = "SELECT cscart_order_data.order_id AS order_id, cscart_orders.total AS total, cscart_order_data.data AS data_serialize, cscart_orders.timestamp AS date, cscart_orders.status AS status FROM cscart_orders
LEFT JOIN cscart_order_data
ON cscart_orders.order_id = cscart_order_data.order_id
WHERE cscart_order_data.type = 'I'
AND cscart_orders.timestamp BETWEEN UNIX_TIMESTAMP('2011-01-01 00:00:00') AND UNIX_TIMESTAMP('2013-01-31 23:59:59') limit 10
";
$resultGetSerialize = $this->db->query($sqlGetSerializedValues);
echo "<pre>";
$var_data = array();
foreach($resultGetSerialize->result_array() as $row1){
$var_data[] = array(
'id' => $row1['order_id'],
'total' => $row1['total'],
'status' => $row1['status'],
'data' => unserialize($row1['data_serialize']),
'date' => $row1['date']
);
}
$range = array();
foreach($var_data as $data){
$id = $data['id'];
$total = $data['total'];
$cost = $data['data']['cost'];
$var_date = $data['date'];
$status => $data['status'];
$date_var = date('Y-m-d H:i:s',$var_date);
$grand_total = $total + $cost;
$cost_ratio = ($cost/$grand_total) * 100;
$paid_ratio = ($total/$grand_total) * 100;
$range[] = $cost_ratio;
$test = array(
'id' => $data['id'],
'ratio' => $cost_ratio,
'status' => $status
);
}
echo "</table>";
print_r($test); //this will return the last index from my array
That;s my problem guys i hope you can help me. Thanks.
$sqlGetSerializedValues = "SELECT cscart_order_data.order_id AS order_id, cscart_orders.total AS total, cscart_order_data.data AS data_serialize, cscart_orders.timestamp AS date, cscart_orders.status AS status FROM cscart_orders
LEFT JOIN cscart_order_data
ON cscart_orders.order_id = cscart_order_data.order_id
WHERE cscart_order_data.type = 'I'
AND cscart_orders.timestamp BETWEEN UNIX_TIMESTAMP('2011-01-01 00:00:00') AND UNIX_TIMESTAMP('2013-01-31 23:59:59') limit 10
";
$resultGetSerialize = $this->db->query($sqlGetSerializedValues);
echo "<pre>";
$var_data = array();
foreach($resultGetSerialize->result_array() as $row1){
$var_data[] = array(
'id' => $row1['order_id'],
'total' => $row1['total'],
'status' => $row1['status'],
'data' => unserialize($row1['data_serialize']),
'date' => $row1['date']
);
}
$range = array();
$test = array();
foreach($var_data as $data){
$id = $data['id'];
$total = $data['total'];
$cost = $data['data']['cost'];
$var_date = $data['date'];
$status => $data['status'];
$date_var = date('Y-m-d H:i:s',$var_date);
$grand_total = $total + $cost;
$cost_ratio = ($cost/$grand_total) * 100;
$paid_ratio = ($total/$grand_total) * 100;
$range[] = $cost_ratio;
$test[] = array(
'id' => $data['id'],
'ratio' => $cost_ratio,
'status' => $status
);
}
echo "</table>";
print_r($test); //this will return the last index from my array
This piece of code is loading a scalar value
$test = array(
'id' => $data['id'],
'ratio' => $cost_ratio,
'status' => $status
);
And should be
$test[] = array(
'id' => $data['id'],
'ratio' => $cost_ratio,
'status' => $status
);
I'm working on this e-commerce site and I'm trying to create a jSON array containing the cart items in PHP.
So far I have:
for ($i=0; $i < count($_SESSION['cart']); $i++) {
$prodid = $_SESSION['cart'][$i][0];
$sizeId = $_SESSION['cart'][$i][1];
$colorId = $_SESSION['cart'][$i][2];
$qty = $_SESSION['cart'][$i][3];
$inslagning = $_SESSION['cart'][$i][4];
$wrapCost += ($inslagning == 'YES' ? 20 : 0);
$row = get_product_buy($prodid, $sizeId, $colorId);
$prodname = $row['prodname'];
$color = $row['color'];
$size = $row['size'];
$prodCatid = $row['catid'];
$image = $row['biggerimage'];
$box = $row['box_number'];
for ($j=0;$j<$qty;$j++) {
$cart = array(
'reference' => '123456789',
'name' => $prodname,
'quantity' => $qty,
'unit_price' => $price,
'discount_rate' => 0,
'tax_rate' => 2500
);
}
}
I know I have the $cart var inside the loop which is probably wrong. The end result should be like this:
$cart = array(
array(
'reference' => '123456789',
'name' => 'Klarna t-shirt',
'quantity' => 1,
'unit_price' => $att_betala * 100,
'discount_rate' => 0,
'tax_rate' => 2500
),
array(
'reference' => '123456789',
'name' => 'Klarna t-shirt',
'quantity' => 1,
'unit_price' => $att_betala * 100,
'discount_rate' => 0,
'tax_rate' => 2500
)
);
All help is appreciated!
You have to append a new child to $cart instead of overwriting it. To append values to an array (the easy way), use $array[] = …. PHP increments the child's ID automatically.
Not required, but please initialize $cart first and use descriptive variables.
To inspect an array (or other data), use var_dump.
// Initialize an empty array. Not needed, but correct to do.
$cart = array();
for ($i=0; $i < count($_SESSION['cart']); $i++) {
$prodid = $_SESSION['cart'][$i][0];
$sizeId = $_SESSION['cart'][$i][1];
$colorId = $_SESSION['cart'][$i][2];
$qty = $_SESSION['cart'][$i][3];
$inslagning = $_SESSION['cart'][$i][4];
$wrapCost += ($inslagning == 'YES' ? 20 : 0);
$row = get_product_buy($prodid, $sizeId, $colorId);
$prodname = $row['prodname'];
$color = $row['color'];
$size = $row['size'];
$prodCatid = $row['catid'];
$image = $row['biggerimage'];
$box = $row['box_number'];
// Append products $qty times.
for ($productCount=0; $productCount<$qty; $productCount++) {
// Append a new product to $cart.
$cart[] = array(
'reference' => '123456789',
'name' => $prodname,
'quantity' => $qty,
'unit_price' => $price,
'discount_rate' => 0,
'tax_rate' => 2500
);
}
}
Use like this
$cart[] = array(
'reference' => '123456789',
'name' => $prodname,
'quantity' => $qty,
'unit_price' => $price,
'discount_rate' => 0,
'tax_rate' => 2500
);
Try Using
for ($j=0;$j<$qty;$j++) {
$cart[] = array(
'reference' => '123456789',
'name' => $prodname,
'quantity' => $qty,
'unit_price' => $price,
'discount_rate' => 0,
'tax_rate' => 2500
);
}
$json_enc = json_encode($cart);
You are not appending to the $cart variable, you are overwriting it on every pass of the loop.
Use the [] syntax to append to an array:
$cart[]=...
Also, its good to declare an empty array at the top of the code:
$cart=array();