简体   繁体   中英

I want to calculate sum from different table

该数据来自不同的表 I want to calculate sum from different table. I'm New in PHP Please help me. Below i have attached screenshot, All the values comes from database.

<table class="table table-bordered" id="sum_table">
    <tr>
    <th style="background-color: #ff7f7f">Items:</th>
    <td style="background-color: #44768e">Amount</td>
    </tr>
        <th>Total</th>
<td><?php

$qry = mysqli_query ("
SELECT sum(Price) 
  FROM rice 
 WHERE date BETWEEN DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') AND DATE_FORMAT(NOW() ,'%Y-%m-01')
");
$row2 = mysqli_fetch_assoc($qry);
echo $row2['total'];


$qry = mysqli_query ("
SELECT sum(Price) 
  FROM egg 
 WHERE date BETWEEN DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') AND DATE_FORMAT(NOW() 
,'%Y-%m-01')
");
$row = mysqli_fetch_assoc($qry);
echo $row['total'];

$total = $row['total'] + $row2['total'];
echo $total;

?></td>
</tr>

</table>

You have 2 issues in your code:

Issue 1: mysqli_query() required 2 parameters, you are not using your connection variable in your mysqli_query()

Issue 2: if you want to sum like $row['total'] + $row2['total']; that then you must need to define alias in your query something like:

SELECT SUM(column) as total FROM tablename

Its better to use PHP error reporting on local environment, this will help you to check actual errors instead of blank pages.

Example:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Edit:

This is good point highlighted by @spencer7593 in comment, you are directly calculating both values, for suppose if your query not returns anything then you will get new error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM