find the sum of value from array - php

I have a cart table and wish to calculate sum of cost wherever I have status=1
id cost status
1 10 1
2 10 1
2 10 1
2 10 2
the code that I tried is
$sql01 = "SELECT * FROM cart where status='1' ";
$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0)
{
while($row = mysqli_fetch_assoc($result01))
{
$price = array_sum($row);
echo "sum of cod:"; echo $price;
echo "<br>";
}
}
the result that I am getting is
10
10
10
The result that should be is
30

One way to do it is to calculate the sum in SQL, as inother answer. If you want to do it in PHP, you can add the cost column to a variable:
$total_cost = 0;
while ($row = mysqli_fetch_assoc($result01)) {
$total_cost += $row['cost'];
}
echo "Result: $total_cost";

You are calculating the sum for each row. Instead you should try this:
$sql01 = "SELECT * FROM cart where status='1'";
$result01 = mysqli_query($con, $sql01);
$cost_array = array();
if (mysqli_num_rows($result01) > 0)
{
while($row = mysqli_fetch_assoc($result01))
$cost_array[] = $row['cost'];
}
echo "Result: ".array_sum($cost_array);
Or (better!) optimize your MySQL query this way:
SELECT sum(cost) finalprice FROM cart where status='1' GROUP BY status
Now you can access your sum using $row['finalprice'].

It's easier than your code: In SQL you should use
"Select sum(cost) from cart where status = '1';"

This is the query for you:
SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status
PHP Code:
$sql01 = 'SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status'
$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0)
{
while($row = mysqli_fetch_assoc($result01))
{
echo 'sum of cod:' . $row['price'] . '<br>';
}
}
Read more about GROUP BY in:
https://dev.mysql.com/doc/refman/5.0/en/group-by-functions-and-modifiers.html

Use this:
SELECT sum(cost) FROM cart group by status having status='1'

Related

Check if last 10 rows duplicated

I'm trying to code a php script, which can find if the last 10 rows from mySQL database are the same. And if the values are same, then the script could sent an email.
I can fetch the last 10 rows.
$sql = ("SELECT ID, DayTime,Temperature FROM AllinOne ORDER BY ID DESC LIMIT 10");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["ID"]. " - DayTime: " . $row["DayTime"]. " - Temperature " . $row["Temperature"]. "<br>";
}
} else {
echo "0 results";
}
Last 10 results:
Now, I'm trying to check if last 10 rows in "Temperature" column are the same (as we can see).
I use:
$sql2 = "SELECT Temperature, COUNT(*) as duplicates FROM AllinOne GROUP BY Temperature ORDER BY ID DESC LIMIT 10";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0)
{
// output data of each row
while($row2 = $result2->fetch_assoc())
{
echo $row2["duplicates"]. "<br>";
}
}
but I can't take back the same results (i can't understand the final result).
$row2 results
Could you help me???
Execute the following query and grab the result:
SELECT
COUNT(*) AS count_rows,
MIN(Temperature) AS min_temperature,
MAX(Temperature) AS max_temperature
FROM (
SELECT *
FROM t
ORDER BY DayTime DESC
LIMIT 10
) AS x
Then send an email if count_rows = 10 and min_temperature = max_temperature.
You just need to fix your second query like:
$sql2 = "SELECT Temperature, COUNT(*) as duplicates
FROM (
SELECT ID, DayTime, Temperature FROM AllinOne ORDER BY ID DESC LIMIT 10
) LastData
GROUP BY Temperature";
Here you can test PHP code with queries

Select Query in Group of 10

I followed one link here, and modified my code accordingly. What I am trying to do achieve is for example a table name media_ids contains 45 rows(which is dyanamic), I want to divide the no of rows in a group of 10 rows minimum (in my case four groups of 10 rows and 1 group of 5) and execute code of each group per hour.
For example from select record from id 1 to 10 then second hour from 11 to 20 and so on unless fetches the last record and start again from id 1.
I added a tracker, which check whats the current limit and proceed.But its giving me the required result what I am trying to achieve.
<?php
require('inc/dbConnect.php');
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointer10=$lastPointer+10;
$currentMediaQuery = "select * from media_ids where id > ".$lastPointer." limit ".$lastPointer.",".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
if ($lastPointer + 10 > 40) {
$lastPointer = 1;
} else {
$lastPointer += 10;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");
?>
I am assuming you are calling this script every hour via ajax/Js...
In your code if you delete some data from another script you may find your first row id i.e 100 !
require('inc/dbConnect.php');
$limit = 10 ;
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointerRes = mysqli_fetch_assoc($lastPointerResult);
$lastPointer = empty($lastPointerRes['tracker']) ? 0 : $lastPointerRes['tracker'] ;
$lastPointer10=$lastPointer* $limit;
$currentMediaQuery = "select * from media_ids limit ".$limit." OFFSET ".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
//do a total row count query here and set as value of $total rather than 40
$total =40 ;
$flag = ceil($total/$limit);
if ($lastPointer == $flag) {
$lastPointer = 0;
} else {
$lastPointer ++;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");

Sort query by time and list next entries

I'm trying to sort this query by time.
I have a gaming match system. And I want to get a list of next 5 matches from my local time zone.
<?php
include_once "include/dbcompo.php";
$q=mysqli_query($con, "SELECT * FROM kamper ORDER BY tid LIMIT 5");
while($row = mysqli_fetch_array($q))
{
$clan1 = $row['clan1'];
$clan2 = $row['clan2'];
$server = $row['server'];
$tid = $row['tid'];
echo $clan1." ".$clan2." ".$server." ".$tid;
echo "<br />";
}
?>
Add a WHERE clause in your query: WHERE tid > NOW().
With NOW() you take the time of the server, maybe you should replace it with new DateTime(null)->getTimestamp()
Something like that:
<?php
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > NOW() ORDER BY tid LIMIT 5');
// or
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > '.new DateTime(null)->getTimestamp().' ORDER BY tid LIMIT 5');
?>
Two options:
1st option: Make the time field a numeric field and sort in PHP:
$queryResult = mysqli_query($con, $query);
while($row = mysqli_fetch_array($queryResult) {
$oldArray[$row['time'] = $row;
}
$array = ksort($oldArray);
foreach($array as $time=>$row) {
// do something
}
2nd option: Make a subquery
SELECT * FROM (
SELECT * FROM kamper WHERE timezone = 'UTC' ORDER BY tid
) LIMIT 5

How to not show the max and mini?

I want to show all the price but not the max and mini.
I'm using NOT IN but it's not working.
<?php $cod_product = $_GET["cod_product"];
$sql = "SELECT `ppm`
,`price`
,`market`
,`product`
,`name_market`
,`cod_market`
FROM ppm, markets
WHERE product=$cod_product AND cod_market=market NOT IN (SELECT MAX(price), MIN(price) FROM ppm)
ORDER BY price ASC";
$result = mysql_query($sql, $connection) or die("fail");
if ($dados = mysql_fetch_array($result)) {
do {
$cod_market = $dados['market'];
$nome_mercado = $dados['name_market'];
$price = $dados['price'];
echo $price;
echo $name_market;
}
while($dados = mysql_fetch_array($result));
}else { }
?>
Change mini() to min() (assuming MySQL).
mini() isn't a function.
Also, some of your SQL doesn't make much sense.
SELECT cod_ppm
,price
,market
,product
FROM ppm
WHERE price NOT IN (SELECT MAX(price), MIN(price) FROM ppm)
ORDER BY price ASC

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