PHP Sum数组 - 仅从DB获得第一个结果

时间:2017-12-07 09:02:15

标签: php mysql

我从我的数据库中取出一个数组,我想总结所有结果,但我似乎只是从数据库获得第一个结果而不是所有结果。

PHP代码:

$jobID = $_GET['jobID'];

$sql_delivqty = "SELECT delQTY
                 FROM deliveries
                 WHERE jobID = '$jobID'
                 ";

$query_delivqty = mysqli_query($conn, $sql_delivqty) or die(mysqli_error($conn));

$row_delivqty = mysqli_fetch_array($query_delivqty);

if ($row_delivqty <= 0) {
    $delivqty = 0;
} else {
    $delivqty = array_sum($row_delivqty);
}

的var_dump:

var_dump($row_delivqty);

array (size=2)
0 => string '560' (length=3)
'delQTY' => string '560' (length=3)

预期结果:

  

560 + 85 + 25 = 670

这与另一个问题不完全相同。建议的问题是尝试在DB中汇总一列。我试图在数据库中对特定行进行求和。

1 个答案:

答案 0 :(得分:0)

在查询中执行SUM: -

$sql_delivqty = "SELECT SUM(delQTY) AS total
                 FROM deliveries
                 WHERE jobID = '$jobID'";

$query_delivqty = mysqli_query($conn, $sql_delivqty) or die(mysqli_error($conn));

$row_delivqty = mysqli_fetch_assoc($query_delivqty);

echo $row_delivqty['total'];

注意: - 此查询易受 SQL Injection 攻击。因此,请使用prepared statements mysqli_* 来阻止它。

参考: - mysqli::prepare Manual

为您的帮助,请执行以下操作(prepared statement way): -

$jobID = $_GET['jobID'];
if ($stmt = mysqli_prepare($conn, "SELECT SUM(delQTY) AS total FROM deliveries WHERE jobID = ?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "i", $jobID);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $row_delivqty);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    echo $row_delivqty['total'];

    /* close statement */
    mysqli_stmt_close($stmt);
}