How to insert multiple data in the database? when I insert data that has multiple orders, only one item is inserted in the database. I need help putting this into a loop.
Here's the code I'm currently using:
foreach ($_SESSION["cart_array"] as $each_items){
$item_id = $each_items['item_id'];
$quantity = $each_items['quantity'] ;
$sql = mysql_query("SELECT * FROM product WHERE id = '$item_id'");
while($row = mysql_fetch_array($sql)){
$product_name = $row['name'];
$price = $row['price'];
$total_price = $price * $quantity;
mysql_query("INSERT INTO customer_order(
id,quantity,item_id,
total_price,shipping_address,
shipping_date,customer_id)
VALUES ('','$quantity','$item_id','$total_price',
'','',
'$lastId')") or die (mysql_error());
}
}
Here's what I tried but it's generating a syntax error:
foreach ($_SESSION["cart_array"] as $each_items){
$item_id = $each_items['item_id'];
$item_id_count = count($item_id) ;
$quantity = $each_items['quantity'] ;
$sql = mysql_query("SELECT * FROM product WHERE id = '$item_id'");
while($row = mysql_fetch_array($sql)){
$product_name = $row['name'];
$price = $row['price'];
$total_price = $price * $quantity;
foreach($i=0,$i < $item_id_count,$i++){
mysql_query("INSERT INTO customer_order(
id,quantity,item_id,
total_price,shipping_address,
shipping_date,customer_id)
VALUES ('','$quantity','$item_id','$total_price',
'','',
'$lastId')") or die (mysql_error());
}
}
}
How can I correctly write the loop?
You have written foreach($i=0,$i < $item_id_count,$i++) where I think you meant
for ($i=0 ; $i < $item_id_count ; $i++ )
Related
I tried to count() the data from database with php but it don't show me the total data but it show the datas.
this is how I count
$query = "SELECT
mitra.*,
user.username,
user.privilege,
user.name
FROM
mitra
INNER JOIN
user ON mitra.id_user = user.id "
$result = $connection->query($query);
if ($result->num_rows > 0) {
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = "" . $row["total_puas"] . "";
$privilege = "" . $row["privilege"] . "";
if ($privilege == 2) :
$calculate = $total / count($id);
var_dump(count($id));
endif;
endforeach;
}
===================
= id = total =
= 1 = 45.84 =
= 2 = 75.45 =
= 3 = 34.54 =
===================
when I var_dumb it it shows int(1)int(1)int(1) not int(3) that what I wanted.
actually I want to count $calculate with the data in $total that should be there is float and the amount from $total that I want to divided with count id
is there any solution that how to count the amount from $total and can be devided with count $id that should be 3?. please help
what I really trying to do from that table example is like 45.84 + 75.45 + 34.54 / 3
Sounds like you want a COUNT() with GROUP BY in your query. Doing count($id) in PHP will always yield one, as its not an array of values.
$query = "SELECT COUNT(id) as cnt, id, total_puas
FROM table
GROUP BY id";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$calculate = $row["total_puas"] / $row['cnt'];
echo $row['id']." has a count of ".$row['cnt'].", a total of ".$row['total_puas']." and calculated to ".$calculate."<br />\n";
}
}
From your updated question, the output becomes a bit more clear. Based on the output data and the result you desire, you want to calculate the sum of all total_paus, divided by the number of rows. You can do this directly in one query, like this
$query = "SELECT SUM(total_puas) / COUNT(u.id) as total
FROM mitra AS m
INNER JOIN user AS u
ON mitra.id_user = user.id";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$total = $row['total'];
echo $total;
You can try this code:
<?php
$i = 0;
$total =0.00;
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()):
if ($row["privilege"] == 2) :
$total = $total + $row["total"];
$i++;
endif;
endwhile;
echo $total."<br>";
echo $i."<br>";
echo $calculate = $total / $i;
}
?>
output
=====================================
$total = 155.83;
$i = 3;
$calculate = $total/$i;
$ans = 51.943333333333;
=====================================
You can try this code:
$query = "SELECT * FROM table"
$result = $connection->query($query);
if ($result->num_rows > 0) {
$total = 0.0;
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = $total + $row['total'];
endforeach;
$calculate = $total / $result->num_rows;
echo $total.<br>;
echo $calclulate;
}
i have two transaction on my cart.
while i click checkout, why $grand total only one inserted to my db.
and when i echo $grand, it appear two total.
this is my function
function cart(){
$username = $_SESSION['UserID'];
$cart = array();
$sql = mysql_query("SELECT * FROM cart WHERE Username='$username'");
while ($r=mysql_fetch_array($sql)) {
$cart[] = $r;
}
return $cart;
}
this is my process code
for ($i = 0; $i < $j; $i++){
echo $start= $cart[$i]['City_Saler'];
echo $end= $cart[$i]['City_Cust'];
$price= $cart[$i]['Price'];
$gram= $cart[$i]['gram'] / 1000;
echo $kg= ceil($gram);
$query= mysql_query("select * FROM service WHERE Start_Destination='$start' AND End_Destination='$end'");
while($query_row = mysql_fetch_assoc($query)){
$grand=$query_row['ServPriceKG'] + $price ;
}
}
for ($i = 0; $i < $j; $i++){
mysql_query("INSERT INTO ordering_detail(ID_Transaction, ID_Product, User_ID, Service_Name, Service_Package, Qty, gram, Price, Receiver_Name, Receiver_City, Receiver_Subdis, Receiver_Address, Receiver_Prov, Receiver_Phone, Grandtotal, Payment, Stat_Transfer_Item, ID_Saler)
VALUES('$idtransaction', '{$cart[$i]['ID_Product']}', '$cusid', '$service', '$paket', '{$cart[$i]['qty']}', '$kg', '{$cart[$i]['Price']}', '$name', '$reci', '$subdis', '$address', '$prov', '$phone', '$grand', '-', '-', '{$cart[$i]['ID_Saler']}')");
}
mysql_query("DELETE FROM preview_ordering WHERE ID_Preview= '$id'");
for ($i = 0; $i < $j; $i++) { mysql_query("DELETE FROM cart WHERE ID = {$cart[$i]['ID']}");}
header('Location:cart.php');
please help me out
I'm trying to write some code that gets random prices from a database until a specific amount is reached. I want it to add the name and price to an array and then print it at the end with $total_items, but it's only showing the last item. What's wrong?
$total = 0;
while ( $total <= $amount ) {
$query = "SELECT name, price FROM table ORDER BY RAND() LIMIT 1";
$run_query = mysql_query($query);
$total_items = array();
while($row = mysql_fetch_assoc($run_query)) {
$total_items[] = $row;
echo $row['name'] . ' / ' . $row['price'] . "<br>";
$total = $total + $row['price'];
}
}
echo "<br>" . Total Amount: ".$total;
print_r($total_items);
variable $total_items is defined in the while loop, so it is truncated in every while loop, and $total_items will only keep the last result.
try to put it above while ( $total <= $amount )
Please define $total_items outside the while loop. And double quote properly to print the output.
$total = 0;
$total_items = array();
while ( $total <= $amount ){
$query = "SELECT name, price FROM table ORDER BY RAND() LIMIT 1";
$run_query = mysql_query($query);
while($row = mysql_fetch_assoc($run_query)) {
$total_items[] = $row;
echo $row['name'] . ' / ' . $row['price'] . "<br>";
$total = $total + $row['price'];
}
} echo '<pre>';echo "Total Amount: ".$total; print_r($total_items);`
When I echo ''.$count.'' its display 11101101. But I want to total count like 8 or 7 etc. What is my wrong here in my code please.
I used to try $count = mysqli_num_rows($u); also but result was same.
my code:
$g = mysqli_query($dbh,"SELECT id FROM update WHERE from_id`='".$b."' OR `to_id`='".$session->id."'") or die(mysqli_error($dbh));
while ($rows = mysqli_fetch_assoc($g)) {
$ids[]= $rows['id'];
}
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
$count = mysqli_affected_rows($dbh);
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
echo ''.$count.'';
}
Assign total count to a variable something like this:
Assumes mysqli_num_rows needs query result $u as argument.
$total = 0;
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
$count = mysqli_num_rows($u);
$count = ($count == "") ? 0 : $count;
$total = $total + $count;
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
}
echo $total;
You will need to change your code a bit like this
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
echo mysqli_num_rows($u);
}
If you need to echo after all foreach statements use this
$count=0;
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
$count = $count + mysqli_num_rows($u);
}
echo $count;
I think your issue is simply formatting bug. Why use the '' here?
Try simply write:
echo $count;
you can simply use
$count=$u->num_rows;
echo $count;
I used following code to get the total price, but it outputs value that is higher than the expected value. What would be the reason for this?
$query = " SELECT *
FROM `mytable`
WHERE `sale_id` = $id";
$result = mysql_query($query);
$item = mysql_fetch_array($result);
foreach ($item as $row) {
$total_price += $row['price'];
}
echo $total_price;
Try this,
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$total_price += $row['price'];
}
echo $total_price;