在日期之间搜索

时间:2014-10-31 13:40:29

标签: php mysql search

我有一个相当棘手的搜索功能,允许用户搜索一个或多个变量:

$where = [];

if( isset( $_POST['destination_search'] )){
$where[] = "`destination` LIKE '%" . mysql_real_escape_string( $_POST['destination_search'] ) . "%'";
}
if( isset( $_POST['cargo_search'] )){
$where[] = "`cargo` LIKE '%" . mysql_real_escape_string( $_POST['cargo_search'] ) . "%'";
}
if( isset( $_POST['dueDate_search_last'] )){
$where[] = "`delivery_date` LIKE '%" . mysql_real_escape_string( $_POST['dueDate_search_first'] ) . "%'";
}

$whereStatement = "";
if( count($where) > 0 )
{
  $whereStatement = "AND" . implode( " AND ", $where );
}

$query_Recordset_table = "
SELECT    *
FROM      `jobs` WHERE bid_deadline >= CURDATE() AND status != 'Offer accepted'
" . $whereStatement . "
ORDER BY `destination` ASC";

用户以下列形式输入搜索字词:

<form id="form_searchJobs" name="form1" method="post" action="">
  <input name="destination_search" type="text" class="bb-input bb-input-large" placeholder="Destination"> <br>
  <input type="text" name="cargo_search" placeholder="Cargo" class="bb-input bb-input-large"> <br>
  <input name="dueDate_search_first" type="text" id="Due_date_from" class="bb-input bb-input-small" placeholder="Due Date (from)"/> <input name="dueDate_search_last" type="text" id="Due_date_to" class="bb-input bb-input-small" placeholder="Due Date (to)"/>
  <input type="submit" name="search" id="search" class="button3" value="Search" />
</form>

我尝试进行以下搜索查询,以便在日期之间进行搜索:

if( isset( $_POST['dueDate_search_first'], $_POST['dueDate_search_last'] )){
$where[] = "`delivery_date` BETWEEN '%" . mysql_real_escape_string( $_POST['dueDate_search_first'] ) . "%' AND '%" . mysql_real_escape_string( $_POST['dueDate_search_last'] ) . "%'";
}

但是他们没有返回任何东西,而且他们也确保其他搜索变量不起作用。我在查询之间搜索有什么问题?

2 个答案:

答案 0 :(得分:1)

这没有意义:

`delivery_date` BETWEEN '%" . mysql_real_escape_string( $_POST['dueDate_search_first'] ) . "%' AND '%" . mysql_real_escape_string( $_POST['dueDate_search_last'] ) . "%'";

%LIKE一起使用..你不能把它扔到任何你想要的地方。

接下来,当使用BETWEEN时,您必须将字符串转换为MySQL可以理解的日期或时间。如果你让用户徒手键入日期,他们很可能不会输入MySQL会理解的东西。

我通常采用的方式是,将日期存储为数据库中的时间戳,为表单使用某种日历选择器JS库,然后将这些日期转换为PHP strtotime()的时间戳。或者其他的东西。然后,您可以在查询中使用这些时间戳。

答案 1 :(得分:0)

$curdate = date('Y-m-d h:i:s');

$query_Recordset_table = "
SELECT * FROM `jobs` WHERE bid_deadline >= $curdate AND status != 'Offer accepted'
" . $whereStatement . "
ORDER BY `destination` ASC";