从同一个表中添加不同的值

时间:2016-01-05 07:26:31

标签: php sql

我有一张桌子。在该表中,有两个名为toamount的字段。我需要显示amount值等于特定值的所有行的to之和。 (说34)。怎么做到这一点?

我到目前为止所做的代码

$result = mysql_query("SELECT * FROM transactions WHERE to = '34'")or die(mysql_error());  
while($row = mysql_fetch_array( $result )) { echo $row['amount']; } ?>

上面的代码给出了每行的amount个体值。但我想要的是这些价值的总和。

The Database

2 个答案:

答案 0 :(得分:2)

使用SUM添加所有金额并回显它

$result = mysql_query("SELECT SUM(amount) as amounts FROM transactions WHERE to = '34'")or die(mysql_error());  
while($row = mysql_fetch_array( $result )) { echo $row['amounts']; } ?>

答案 1 :(得分:0)

我建议您使用mysqli_*PDO,因为mysql_*已被弃用, PHP 7 中不可用。

以下是使用MYSQLi Object Oriented

的完整代码示例
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT SUM(amount) as amounts FROM transactions WHERE to = 34";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo $row['amounts']. "<br>";
    }
} 
else 
{
    echo "0 results";
}
$conn->close();

?>