Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

php - Find the sum of values inside array

I am trying to select and sum subtotal from the cart table, but we are unable to sum

<?php
    // This will get all related products
    mysqli_select_db($conn, $dbname);
    $query_gettotal = "SELECT subtotal FROM cart WHERE scode ='$gu'";
    $gettotal = $conn->query($query_gettotal);
    $row_gettotal = mysqli_fetch_assoc($gettotal);
    do{ 
    $a = array($row_gettotal['subtotal']); 
    foreach ($a as $value) {
    //print $value;
    //print_r($a);
    //getting value 190047509503800
    // how to add 1900 4750 950 3800
    
    }
    } while ($row_gettotal = mysqli_fetch_assoc($gettotal));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use a prepared statement to avoid any risk of SQL injection. You can also directly the sum the values in your query:

$query_gettotal = "SELECT SUM(subtotal) AS total FROM cart WHERE scode = ?";
$stmt = $conn->prepare($query_gettotal);
$stmt->bind_param('s', $gu);
$stmt->execute();
$result = $stmt->get_result();
$row_gettotal = $result->fetch_assoc();
$total = $row_gettotal['total'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...