1

如何从 TOTAL AMOUNT RECEIVED 中减去 TOTAL EXPENSES 并将其显示在 TOTAL REVENUES 中?

数据来自我数据库中的不同表。不幸的是,我无法上传图片以获得更清晰的视图。

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>
4

2 回答 2

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'
于 2013-02-02T08:51:36.757 回答
0

我将制定独立于结构/样式的一般答案,但本质上你想存储前两个查询的返回值,然后做一些数学运算。让我们先把它简单化(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_ 库,使用 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 函数。

于 2013-02-02T08:34:44.797 回答