基於查詢的方法:
高效檢索列,利用SQL內建的聚合函數:
SELECT SUM(column_name) FROM table_name;
PDO實作:
// Prepare the query $stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes'); // Execute the query $stmt->execute(); // Fetch the results $row = $stmt->fetch(PDO::FETCH_ASSOC); // Retrieve the sum $sum = $row['value_sum'];
mysqli實作:
// Execute the query $result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes'); // Fetch the results $row = mysqli_fetch_assoc($result); // Retrieve the sum $sum = $row['value_sum'];
注意:
以上是如何使用 PHP 計算 MySQL 中的欄位總和?的詳細內容。更多資訊請關注PHP中文網其他相關文章!