如何使SUM可见?

时间:2018-03-24 17:44:15

标签: php mysql mysqli sum

我是php和mysql的新手,也是这个网站的新手。所以我希望我做的一切都很好。

我试图在列中获取某些值的SUM。但我在网站上看不到任何结果。我正在尝试一周,现在搜索了很多信息和主题,但到目前为止还没有结果。所以我想请求你,希望有人能看到我做错了什么。

这就是我现在所拥有的。

<?php
$con=mysqli_connect("localhost","user","1234","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$res = mysqli_query($con,"SELECT SUM(Bedrag) FROM `Uitdraai` WHERE Datum BETWEEN '2018-01-01' AND '2018-03-01'");
if (FALSE === $res) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($res);
$sum = $row[0];

mysqli_close($con);
?>

我已经在以下页面上尝试了几乎所有选项,但到目前为止还没有运气。我只是得到我的常规网页而没有答案。

Get sum of MySQL column in PHP

Single Result From SUM With MySQLi

我真的很感激!

2 个答案:

答案 0 :(得分:0)

SELECT SUM(Bedrag) AS value_sum  FROM `Uitdraai` WHERE Datum BETWEEN '2018-01-01' AND '2018-03-01;

在PHP代码中,试试这个:

$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$result = mysqli_query($con,'SELECT SUM(Bedrag) AS value_sum  FROM `Uitdraai` WHERE Datum BETWEEN '2018-01-01' AND '2018-03-01'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];
echo $sum;

使用PDO(折旧mysql_query)

$stmt = $handler->prepare("SELECT SUM(Bedrag) AS value_sum  FROM `Uitdraai` WHERE Datum BETWEEN '2018-01-01' AND '2018-03-01");
$stmt->execute();

$row = $handler->fetchAll(PDO::FETCH_OBJ);
$sum = $row->value_sum;
echo $sum;

答案 1 :(得分:0)

您应该知道mysql_connect是从 php 7或更高版本折旧的。为此,您需要使用 mysqli pdo 与服务器进行交互。

您可以尝试以下代码从数据库中获取总和。

    $con = new mysqli("localhost", "my_user", "my_password", "my_db");
    $sql = "SELECT SUM(Bedrag) AS value_sum  FROM Uitdraai WHERE Datum BETWEEN '2018-01-01' AND '2018-03-01'";

    $stmt = $con->query($sql);
   if($stmt){
       $result = $stmt->fetch_assoc();
       echo $result['value_sum'];
    }