我有一张桌子。在该表中,有两个名为to
和amount
的字段。我需要显示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
个体值。但我想要的是这些价值的总和。
答案 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();
?>