PDO SUM MYSQL table

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s