php – PDO SUM MYSQL表

我正在学习,因为我去了,并且在过去的几天里一直在研究代码片段,现在我已经抛出了一块寻求帮助.

我试图使用PDO计算数据库中2列的总和.

这是我的代码

<?php
$host = "localhost";
$db_name = "dbname";
$username = "root";
$password = "root";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

// show error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}

$query = "SELECT SUM (fill_up) AS TotalFill, 
                 SUM (mileage_covered) AS Totalmiles 
                 FROM fuel_cost";

$row = $query->fetch(PDO::FETCH_ASSOC);
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];           
$myanswer = $total_fill/$total_miles;

//display the answer
echo $myanswer               
?>

我还检查了我的数据库表,两列都是varchar(32)

我得到的错误是调用非对象上的成员函数fetch()
我已经搜索过这个但不确定上面代码的问题是什么
先感谢您

最佳答案 试试这个代码: –

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT SUM (fill_up) AS TotalFill, 
                 SUM (mileage_covered) AS Totalmiles 
                 FROM fuel_cost";
$result = $conn->query($sql);

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

        $total_fill = $row['TotalFill'];
        $total_miles = $row['Totalmiles'];
        $myanswer = $total_fill / $total_miles;

//display the answer
        echo $myanswer;
        die;
    }
} else {
    echo "0 results";
}
$conn->close();
?>
点赞