pdo SELECT SUM(col1) WHERE
I'm having a little trouble querying a database when I have check if a
date is between two dates. I've searched high and low and have been stuck
on this since last night, I have to accept defeat and ask for help.
My table looks like this
Col1 col2 Date
----- ------ ------
ABC 2 2011-01-01 00:00:00
ABA 3 2010-01-01 00:00:00
ADD 1 2009-01-01 00:00:00
AED 3 2013-01-01 00:00:00
ABC 2 2013-01-01 00:00:00
ABA 3 2012-01-01 00:00:00
ADD 1 2013-01-01 00:00:00
AED 3 2013-01-01 00:00:00
PHP
try {
$dbh = $DBConnection;
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$FromDate = "2013-01-01 00:00:00";
$EndDate = "2014-01-01 00:00:00";
$stmt = $dbh->prepare("SELECT Col1, SUM(Col2) FROM table WHERE Date >
:FromDate AND Date < :EndDate");
/*** bind the paramaters ***/
$stmt->bindParam(':FromDate', $FromDate, PDO::PARAM_STR);
$stmt->bindParam(':EndDate', $EndDate, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$stmt->execute();
/*** fetch the results ***/
$result = $stmt->fetchAll();
/*** loop of the results ***/
foreach($result as $row)
{
echo $row['Col1'].' - '.$row['SUM(Col2)'];
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Desired result
AED 6
ABC 2
ADD 1
If I do this with code that selects all, the sum works fine and everything
is as desired. I'm trying a different approach with WHERE and pdo bind so
then I can limit the results to a date range. I'm just coming over from
Mysql to PDO and struggling a little.
My code above currently returns the first record within the database with
all their values combined.
No comments:
Post a Comment