Table PDO SUM MYSQL

I study when I leave and collect code fragments when I leave and work on it for the last few days, and now I have thrown my towel in search of help.

I am trying to calculate the sum of two columns in my database using PDO.

here is my code

<?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               
?>

I also checked the database table and both columns are varchar (32)

The error I get is that Call to a member function fetch() on a non-object I was looking for this, but not sure if the problem with the above code is thanks in advance

+4
source share
1 answer

Try this code: -

<?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();
?>
+2
source

Source: https://habr.com/ru/post/1613632/


All Articles