如何从收到的总金额中减去总金额并将其显示在总收入上?
数据来自我的数据库中的不同表格..很遗憾,我无法上传图片以获得更清晰的视图..
TOTAL AMOUNT RECEIVED || 15610
TOTAL EXPENSES || 11300
TOTAL REVENUES || (this must be equal to TOTAL AMOUNT RECEIVED - TOTAL EXPENSES)
这是我的代码:
<table width="383" border="1" bordercolor="#00CCFF">
<tr>
<td width="245" bgcolor="#0099FF">TOTAL AMOUNT RECIEVED</td>
<td width="128" bgcolor="#FFFFFF">
<?php
include("confstudents.php");
$id = $_GET['id'];
$query = "SELECT id, SUM(1stPayment + 2ndPayment + 3rdPayment + 4thPayment) um_payment FROM student_payments";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "" . $row['sum_payment'];
echo "<br/>";
}
?>
</td>
</tr>
<tr>
<td bgcolor="#0099FF">TOTAL EXPENSES</td>
<td bgcolor="#FFFFFF">
<?php
include("confexpenses.php");
$id = $_GET['id'];
$query = 'SELECT SUM(piece * price) tprice FROM expenses';
$result = mysql_query($query) or die(mysql_error());
while($res = mysql_fetch_assoc($result)){
echo " " . $res['tprice']; " ";
}
?>
</td>
</tr>
<tr>
<td bgcolor="#0099FF">TOTAL REVENUES</td>
<td bgcolor="#FFFFFF">
<?php
include("totalrev.php");
?>
</td>
</tr>
</table>
答案 0 :(得分:0)
我将找出独立于结构/样式的一般答案,但实际上你想要从frist两个查询存储返回值,然后做一些数学运算。让我们先简单一点(KISS - Keep It Simple,Stupid),并从样式中抽象出逻辑。
<?php
$query = "
SELECT
id,
SUM(1stPayment + 2ndPayment + 3rdPayment + 4thPayment) AS sum_payment
FROM
student_payments";
$result = mysql_query($query) || die(mysql_error());
// Create a variable to store the sum of payments
$sum_payment = 0;
// Print out result
while($row = mysql_fetch_array($result))
{
echo "" . $row['sum_payment'];
echo "<br/>";
$sum_payment += (int)$row['sum_payment'];
}
$query = 'SELECT SUM(piece * price) tprice FROM expenses';
$result = mysql_query($query) or die(mysql_error());
// Variable to store the expenses
$expenses = 0;
while($res = mysql_fetch_assoc($result))
{
echo " " . $res['tprice']; " ";
$expenses += $res['tprice'];
}
// Calculate the difference
$total_rev = $sum_payments - $expenses;
echo '<br/>', $total_rev, '<br/>';
?>
关于你使用$_GET['id']
的说明 - 如果你计划引入一些最终会进入SQL查询的东西,你应该逃避它:使用mysql_ library,使用mysql_real_escape_string http://php.net/manual/en/function.mysql-real-escape-string.php但是,一般来说,你应该切换到使用MySQLi库 - http://www.php.net/manual/en/book.mysqli.php - 因为它更安全,最终PHP不支持标准的mysql函数。
答案 1 :(得分:0)
如果两个表之间存在关系,例如id:
SELECT
SUM(r.stPayment) as RECIEVED, sum(e.piece * e.price) as EXPENSES
FROM
student_payments as r,
expenses as e
WHERE r.id = e.id and r.id = '$id'