sum of two column values in mysql using php

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
newbaba
Forum Newbie
Posts: 17
Joined: Thu Jan 26, 2017 10:36 pm
Location: Karachi

sum of two column values in mysql using php

Post by newbaba »

I am very thankful and grateful to this site and the moderators which have helped me alot i am still a beginner in php mysql
i will be very thankful if you could help in the following code
the error

Code: Select all

<?php


$thehost = 'localhost';
$dbname = 'tutorial';
$username = 'root';
$userpass = '';

$dbh = new PDO ("mysql:host = $thehost ; dbname = $dbname", $username, $userpass)
or die ("Error");
foreach($dbh->query('SELECT SUM(option1+option2) FROM feedback') as $row)
{
echo "<tr>";
echo "<td>" . $row['SUM(option1+option2)'] . "</td>";
echo "</tr>"; 
}
?>

Basically i want to add the values of two columns and print them
but the error i am facing is
Warning: Invalid argument supplied for foreach()
and neither its adding up
thanks alot in advance
User avatar
Christopher
Site Administrator
Posts: 13595
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: sum of two column values in mysql using php

Post by Christopher »

Code: Select all

$dbh = new PDO ("mysql:host = $thehost ; dbname = $dbname", $username, $userpass)
or die ("Error");
foreach($dbh->query('SELECT (SUM(option1)+SUM(option2)) AS total FROM feedback') as $row)
{
echo "<tr>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>"; 
}

Usually with SUM() you need to GROUP BY an appropriate column.
(#10850)
newbaba
Forum Newbie
Posts: 17
Joined: Thu Jan 26, 2017 10:36 pm
Location: Karachi

Re: sum of two column values in mysql using php

Post by newbaba »

thanks for your prompt reply . i m facing this error when running the code
Warning: Invalid argument supplied for foreach()
thanks in advance
User avatar
Christopher
Site Administrator
Posts: 13595
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: sum of two column values in mysql using php

Post by Christopher »

See what $dbh->query() is returning:

Code: Select all

$dbh = new PDO ("mysql:host = $thehost ; dbname = $dbname", $username, $userpass)
or die ("Error");
echo "<pre>" . print_r($dbh->query('SELECT (SUM(option1)+SUM(option2)) AS total FROM feedback'), 1) . "</pre>";
(#10850)
newbaba
Forum Newbie
Posts: 17
Joined: Thu Jan 26, 2017 10:36 pm
Location: Karachi

Re: sum of two column values in mysql using php

Post by newbaba »

thanks it did my work
Post Reply