user20929302
user20929302

Reputation: 403

php-sql where option for selecting date range

In my php page I create a drop down to select either all or a select all data greater than X number of days ago, say 10. Im looking for a simplified way to run my query instead of what I have done.

What I have created is, this works I am just seeing if there is an option to simplify this query:

if($dropDownInput == 'All'){
   $db_query = mysqli_query("SELECT Name, MAX(Date), SUM(Iteratitions)
                             FROM my_table
                             GROUP BY Name, Date")
} else{
   $db_query = mysqli_query("SELECT Name, MAX(Date), SUM(Iteratitions)
                             FROM my_table
                             WHERE Date >= (CURDATE() - INTERVAL $range day)
                             GROUP BY Name, Date")
}

Upvotes: 1

Views: 38

Answers (1)

Travis
Travis

Reputation: 687

Something along the lines of:

$sql = SELECT Name, MAX(Date), SUM(Iteratitions)
                         FROM my_table
if($dropDownInput != 'ALL'){
    $sql.= " WHERE WHERE Date >= (CURDATE() - INTERVAL $dropDownInput day)
}
$sql.="GROUP BY Name, Date"

$db_query = mysqli_query($sql)

Upvotes: 1

Related Questions