2

我正在使用包含这些表的数据库:

CREATE TABLE required_items(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    required_amount INT NOT NULL
);

CREATE TABLE donations(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    donation_amount INT NOT NULL,
    item_id INT NOT NULL,
    FOREIGN KEY(item_id) REFERENCES required_items(id)
);

在网页上有一个表格,列出了所需的项目和剩余的金额。然后,用户可以承诺捐赠一定数量的他们选择的任何物品。到目前为止,我的代码正确显示了所有必需的项目,但它没有适当地更新。

if(!empty($_REQUEST['donate']))
    {
        $sql = "INSERT INTO donations (name, email, donation_amount, item_id) VALUES (?, ?, ?, ?)";
        $query = $db->prepare($sql);
        $query->execute(array($name, $email, $donation_amount, $item_id));

        echo("Thank you for donating!\n<br>\n<br>");
    }

    $request = "SELECT 
                required_items.id,
                required_items.name, 
                required_items.required_amount - COALESCE(donations.donation_amount, 0) AS Amount_Left
                FROM required_items LEFT JOIN donations ON donations.item_id=required_items.id ORDER BY id ASC";

    $stmt = $db->query($request);
    $item_info = $stmt->fetchAll();

    } catch (PDOException $e) {
        echo "Exception: " . $e->getMessage();
    }

    // Round negative amounts to zero
    if($item_info['Amount_Left'] < 0){
        $item_info['Amount_Left'] = 0;
        }
?>
    <form name="donationForm" action="<?php $pageName ?>" method="POST">
    <fieldset>
    <table border="1">
        <tbody>
            <tr>
                <td width="200">Item Name</th><td width="100">Amount</th><td width="0"></th>
            </tr>
            <?php
                foreach ($item_info as $row):{
                    echo("<tr><td>" . $row['name'] . "</td>");
                    echo("<td>" . $row['Amount_Left'] . "</td>");
                    echo("<td><input type=\"radio\" name=\"radioButtons\" value=\"". $row['id'] ."\"></input></td></tr>\n");
                } endforeach;
            ?>
        <tbody>
    </table>

如果我“捐赠”一次,表格会正确更新,从所需金额中减去捐赠。但是,如果我再次捐赠相同的物品,表格行会重复,并且不会从所需金额中减去新的捐赠。我认为 INSERT ON DUPLICATE KEY UPDATE 可能有效,但我无法理解。我怎样才能让这个表正确显示?

编辑:澄清一下,我使用 COALESCE 的原因是因为捐赠表中没有任何内容,直到有人捐赠了一些东西。因此,由于捐赠表中的值最初为空,因此无法计算等式。

编辑2:我想问题就变成了,在这种情况下我应该什么时候合并?

4

1 回答 1

3

You would want to use SUM() instead of COALESCE(). All COALESCE() does is return the first not-null value.

于 2013-09-17T21:07:11.983 回答