Page 1 of 1

sum of two column values in mysql using php

Posted: Mon Feb 13, 2017 1:47 pm
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

Re: sum of two column values in mysql using php

Posted: Tue Feb 14, 2017 1:03 am
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.

Re: sum of two column values in mysql using php

Posted: Tue Feb 14, 2017 6:31 am
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

Re: sum of two column values in mysql using php

Posted: Tue Feb 14, 2017 11:22 pm
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>";

Re: sum of two column values in mysql using php

Posted: Sun Feb 26, 2017 9:41 am
by newbaba
thanks it did my work