Issue with php array_sum displaying multiple values - php

I'm having an issue with with a PHP function displaying multiple sums instead of just one when I use array_sum. I'm using phpMyAdmin and the two database tables for this function. These are the tables:
games:
cart:
function total_price() {
$total = 0;
global $con;
$ip = getIP();
$select_price = "select * from cart where ip_add = '$ip'";
$run_price = mysqli_query ($con, $select_price);
while ($g_price = mysqli_fetch_array($run_price)) {
$Cart_Game_ID = $g_price['g_ID'];
$cart_price = "select * from games where Game_ID = '$Cart_Game_ID'";
$run_game_price = mysqli_query($con, $cart_price);
while($pp_price = mysqli_fetch_array($run_game_price)){
$Game_Price = array($pp_price['Game_Price']);
$values = array_sum($Game_Price);
$total += $values;
}
echo "$" . $total;
}
}
Every game in my database costs $20. There are currently 5 games in my database. When I run this function I get $20$40$60$80$100. All i need is the $100. Not the previous 4 sums.

Move this outside the While Loop:
echo "$" . $total;

Related

how to sum values of total column, i.e calculate the sub total? as total is not from database

enter image description here*now how can i calculate the sub total of the (tolal) field values these values are not from database, these are from (price of item * quantity)*
This is my code:
<?php
$ipAdd = getRealIpAddr();
$checkPrice= "select * from cart where ipAdd= '$ipAdd' ";
$run= mysqli_query($conn,$checkPrice);
while($record= mysqli_fetch_array($run)){
$proId= $record['pId'];
$cId= $record['cId'];
$cQuant= $record['qnty'];
$proPric= "select * from products where prodId= '$proId' ";
$runPrice=mysqli_query($conn, $proPric);
while($pPrice=mysqli_fetch_array($runPrice)){
$proPri= $pPrice['prodPrice'];
$t = $proPri* $cQuant ;
}
}
?>
Alrighty, so assuming you want total of all items times all the quantities, here's what you do:
$ipAdd = getRealIpAddr();
$total = 0;
$checkPrice = "SELECT * FROM cart WHERE ipAdd = '$ipAdd' ";
$run = mysqli_query($conn,$checkPrice);
while($record = mysqli_fetch_array($run)){
$proId = $record['pId'];
$cId = $record['cId'];
$cQuant = $record['qnty'];
$proPric = "SELECT * FROM products WHERE prodId = '$proId' ";
$runPrice = mysqli_query($conn, $proPric);
$pPrice = mysqli_fetch_array($runPrice);
$proPri = $pPrice['prodPrice'];
$t = $proPri * $cQuant ;
$total += $t;
}
echo $total; // will be a sum of all prices times all quantities
You don't need while if you're fetching just one value, literally just removing it works fine
You start this process by declaring $total variable, in this case resetting it
You do everything you already did, after which you increment $total by whatever is the value of $t
Keep in mind that $total will change during this while loop, so considering this looks like a per-user-query, make sure to use it outside of the loop.

How to combine multiple SQL SELECT results into one array in PHP?

Hello this code works but currently it is very repetitive.
I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.
I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(
I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
// Select data from table from a random row
$grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
$grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
$grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
$grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
$grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
$grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";
$result1 = $mysqli->query($grab1);
$result2 = $mysqli->query($grab2);
$result3 = $mysqli->query($grab3);
$result4 = $mysqli->query($grab4);
$result5 = $mysqli->query($grab5);
$result6 = $mysqli->query($grab6);
// Convert result into an array called items
$item1 = mysqli_fetch_row($result1);
$item2 = mysqli_fetch_row($result2);
$item3 = mysqli_fetch_row($result3);
$item4 = mysqli_fetch_row($result4);
$item5 = mysqli_fetch_row($result5);
$item6 = mysqli_fetch_row($result6);
I managed to solve this with help on this thread..
I replaced all this code with:
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
foreach ($ran_num as $key => $value) {
$grab[$key] = "select * from stock_tbl where stock_id='$value'";
$result = $mysqli->query($grab[$key]);
$item[$key] = mysqli_fetch_row($result);
}
Thank you very much :)
First of all, do you really need *?
What's wrong with using a single query with the IN() function? For example:
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
// Select(grab) data from table from a random row
$grab = 'SELECT * FROM stock_tbl WHERE stock_id IN ('.implode(',', $ran_num).')';
<?php
$ran_num = (RandomInRange(1,$total,6));
foreach ($ran_num as $key => $value)
{
$grab[$value] = "select * from stock_tbl where stock_id='$value'";
}
?>
If you don't need to access each statement individually, this is also possible:
<?php
$ran_num = (RandomInRange(1,$total,6));
$grab = '';
foreach ($ran_num as $key => $value)
{
$grab .= "select * from stock_tbl where stock_id='$value';";
}
?>
That's essentially creating one long string that SQL will parse as individual commands using the semi-colon as the delimiter for each one.
You can concatenate strings in PHP with the '.' operator. Also, setting the grab variables as an array will make this easier as well, if that is possible in your implementation. You're probably looking for code such as:
for (int i=0; i < 20; i++)
$grab[i] = "select * from stock_tbl where stock_id='$ran_num[".i."]'";

total array sum using pdo

I'm trying to get total price from cart table. The product_price in other table which is product. I'm only getting the latest price not the total price. Thanks
// function total_price (){
$total = 0;
global $db;
$ip = getIp();
$sql = $db->query("SELECT * from cart WHERE ip_add='$ip'");
$no=$sql->rowCount(); // number of rows affected by the last SQL statement
if ($no == 0){
echo "";
} else {
foreach($sql as $row)
$product_id = $row["p_id"];
$sql = $db->query("SELECT product_price from product WHERE product_id='$product_id'");
$no=$sql->rowCount(); // number of rows affected by the last SQL statement
if ($no == 0){
echo "";
}
else
{
foreach($sql as $row)
$product_price = array($row["product_price"]);
$values = array_sum($product_price );
$total += $values;
}
}
echo "RM" . $total;
}
if I'm reading the structure right this one query should be all you need:
select sum(product_price) from product
inner join cart on product.product_id=cart.product_id

Loop through results from mysql, and sum values

I use a while loop to process table record like this:
$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
while ($show_s = mysqli_fetch_assoc($result)) {
$quantity = $show_s['sells_quantity'];
}
mysqli_free_result($result);
}
I have all my table records, and now I want to sum up all quantity fields , but I don't know how to do it.
For example, if I got 10 records quantity for records like 2, 1, 5, 1, 3, 6 etc, I would like to sum them like this: 2+1+5+1+3+6 = 18
If you can do something in mysql - do it. Use SUM aggregation function:
$get_s = "SELECT SUM(sells_quantity) as sells_sum FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
$show_s = mysqli_fetch_assoc($result);
echo $show_s['sells_sum'];
}
mysqli_free_result($result);
Still, if you need certain values of rows - you can count sum in a loop:
$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
$total = 0;
while ($show_s = mysqli_fetch_assoc($result)) {
$quantity = $show_s['sells_quantity'];
$total += $quantity;
}
mysqli_free_result($result);
echo $total;
}
But mysql SUM() is preferrable.

php math question

I have a db table which have a row of a product amount. I want to create a loop that will calculate for me the sum for all the amounts.
$results = mysql_query("SELECT *
FROM prod");
while($info = mysql_fetch_array($results)) {
$amount = $info['amount'];
}
amount is the var for each product cost. I want to get a sum for all the vars together - how can I do it?
Use the SUM() function in a SQL query.
$result = mysql_query("SELECT SUM(amount) AS sum_amount FROM prod");
if ( $result )
$sum = mysql_result($result, 0, 0);
Easier to do in MySQL:
SELECT SUM(amount) FROM prod
Then fetch the result.
First:
You can do this with mysql
SELECT SUM(amount) FROM ....
Second:
while ($info = mysql_fetch_array($results)) {
$amount[] = $info['amount'];
}
$sum = array_sum($amount);
You can add the amounts to a variable:
$results = mysql_query("select * from prod");
$sum = 0
while($info = mysql_fetch_array($results)) {
$amount = $info['amount'];
$sum += $amount
}
Or you can do it in SQL:
SELECT SUM(column) FROM table

Categories