I have a search form with several input fields. 2 of these input fields are dates. If a users fills in the From/To date, all records from/untill that date should be shown; if a users gives 2 dates, all records between these 2 dates should be shown.
This is my working code for the other input fields, but I have no idea how to implement the date constraints. The parameter binding should stay dynamic since we don't know on how many variables the user will search.
<?php $this->databaseConnection();
$sql = 'SELECT * FROM trips t';
$searchTerms = array_filter($_GET);
$whereClause = array();
foreach($searchTerms as $key=>$value)
{
//Push values to array
array_push($whereClause, "t." . $key . "=:" . $key);
}
if(!empty($whereClause))
{
$sql .= " WHERE " . implode(" AND ", $whereClause);
}
if($this->databaseConnection()) {
$query_search_data = $this->db_connection->prepare($sql);
foreach($searchTerms as $key=>$value)
{
$query_search_data->bindValue(':' . $key, $value);
}
$query_search_data->execute();
$result = $query_search_data->fetchAll(); ?>
I found the solution.
Unset the date variables (eg unset($searchTerms['fromDate'], $searchTerms['toDate']);
) and add them again at the end of the query.
if (isset($_GET['fromDate']) && !empty($_GET['fromDate'])) {
$sql .= " AND Date >=:from_date";
}
Hope this can help other people with dynamic parameter binding issues.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.