使用PHP和MySQL创建动态搜索查询

问题描述:

我正在尝试根据用户输入创建动态搜索查询.

I'm trying to create a dynamic search query, based on the user input.

  • 用户可以不填写任何,部分或全部字段.
  • 查询在表中搜索符合所有要求的记录.

现在我已经完成了研究,并且发现了执行此操作的多种方法.但是它们都不起作用,如果起作用了,那将是不切实际的.

Now I have done my research, and I found out multiple ways on doing this. But none of them work, and if they do, they are far from practical.

此刻,我正在创建如下查询:

At the moment I'm creating a query like this:

SELECT * 
FROM assignments 
WHERE (id = $id OR id = '') 
  AND (field1 = $field1 OR field1 = '')

该查询有效,但前提是您填写了所有字段.

This query works, but only if you fill in all the fields.

我从*文章中得到了这个,我现在找不到了,它说:

I got this from a * article, that I can't find anymore, that said:

如果用户填写了输入字段,它将检查第一条规则 "id = $ input" 如果用户未指定任何输入,它将检查"id ="和何时输入 检查,它将只返回所有内容.因为它逃脱了空的搜索规则.

If the user has filled in an input field it will check the first rule "id = $input" and if the user hasn't specified any input it will check for "id = '' " and when it checks for that, it will just return everything. Because it escapes the empty search rule.

但是您可能已经知道,它不起作用.

But as you might already know, it doesnt work..

您如何建议我解决这个问题?

How would you suggest me to approach this?

尝试获取所有发布变量,并遍历它们以查看它们是否有效,然后构建查询

Try getting all of the post vars and looping through them to see if they are valid, and then build your query

<?php
$id = $_POST[id];
$field1 = $_POST[field1];
$field2 = $_POST[field2];
$field3 = $_POST[field3];

$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";

$whereStr = implode(" AND ", $whereArr);

$query = "Select * from assignments WHERE {$whereStr}";

类似的东西应该可以满足您的需求

Something like that should handle what you need