简体   繁体   中英

Getting sum() of all values in a column of a mySQL database

if ($result->num_rows > 0) { // output data of each row

while($row = $result->fetch_assoc()) { $miles[] = $row['totalDistance'];

} Echo $result;I am struggling to get my code to work, I am trying to output the total of all of the values in the 'distance' column of my database.

I get the error notice: "undefined variable: miles"

This is my code:

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 


$sql = "SELECT sum(distance) AS totalDistance FROM strava";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) { $miles[] = $row['totalDistance'];
}
Echo $result;
}
?>

You don't appear to assign a value to $miles anywhere. Do you perhaps mean to use $result instead?

构造$miles[] =是将新元素追加到数组$miles的快捷方式,但是您尚未定义$miles ,因此在该行代码中未定义$miles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM