4

I am learning as i go and been picking up snippets of code as i go and been working on this for the past few days and now i have thrown the towel in to seek help.

I am trying to calculate the sum of 2 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 have also checked my database table and both columns are varchar(32)

the error I am getting is Call to a member function fetch() on a non-object I have searched into this but not sure what's the issue with the above code Thank You in advance

1 Answers1

2

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();
?>
Abhishek Sharma
  • 6,689
  • 1
  • 14
  • 20