使用php和mysql在数据库中搜索

时间:2014-10-01 09:20:58

标签: php mysql

我想创建一个搜索数据库表的搜索功能。

以下表单提交搜索参数:

<form id="form_searchJobs" name="form1" method="post" action="">
  <label id="destinationLabel">Destination</label> <input name="destination_search" type="text" id="destination_search"/> <br/>
  <label id="cargoLabel">Cargo</label> <input type="text" name="cargo_search" id="cargo_search"/> <br/>
  <label id="deadlineLabel">Deadline</label> <input type="text" name="deadline_search" id="datepicker"/> <br/>
  <input type="submit" name="search" id="search" class="button3" value="Search"  onClick="showSearchedString()"/>
  <a href="../Jobs.php" id="clearSearch" class="button3">Clear Search</a>
</form>

搜索功能应该允许您单独搜索每个文本字段或同时搜索所有文本字段。

我有以下数据库查询:

if (isset($_POST['destination_search']) || (isset($_POST['cargo_search']) || (isset($_POST['deadline_search'])))) {
  $destination_search = $_POST['destination_search'];
  $cargo_search = $_POST['cargo_search'];
  $deadline_search = $_POST['deadline_search'];
  $newDate = date("y-m-d", strtotime($deadline_search));
  $query = sprintf("SELECT * FROM jobs WHERE destination LIKE %s OR jobs.cargo LIKE %s OR RSVP_date LIKE %s ORDER BY destination ASC", GetSQLValueString("%" . $destination . "%", "text"),GetSQLValueString("%" . $deadline_search . "%", "text"),GetSQLValueString("%" . $newDate . "%", "text"));
}
else {
$query = "SELECT * FROM jobs ORDER BY destination ASC";
}

但是此查询显示所有结果,无论搜索条件如何。我的查询有问题,但我现在不知道是为了同时搜索单个变量还是所有变量?

1 个答案:

答案 0 :(得分:1)

如果是你的destination_search包含文本但你的cargo_search和deadline_search没有,你输出的查询将是这样的:

$where = [];

if( isset( $_POST['destination_search'] )){
    $where[] = "`destination_search` 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['deadline_search'] )){
    $newDate = date("y-m-d", strtotime( $_POST['deadline_search'] ));
    $where[] = "`RSVP_date` LIKE '%" . mysql_real_escape_string( $_POST['deadline_search'] ) . "%'";
}

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

$query = "
    SELECT    *
    FROM      `jobs`
    " . $whereStatement . "
    ORDER BY `destination` ASC";

这会更好吗?