PHP SQL搜索表单语法


PHP SQL Search Form Syntax

我有一个php表单,用于搜索SQL数据库。有八个表单字段,每个字段都是可选的。如果所有内容都为空,则查询将返回整个数据库。如果填写了一个字段,它将按一个字段过滤,按两个字段过滤等等。在我想要搜索空条目之前,我没有遇到任何问题。例如,我想搜索客户有姓氏但没有主要电话号码的地方。我已经工作了几个小时,想不出一个简单的方法来实现这样的东西。我设想它是当你在搜索字段中键入一个关键字来搜索项目为空的地方。所以,如果我把"Smith"放在姓氏中,把"NULL"放在电话号码中,这将适用于我上面的例子。下面是我当前的代码。

$query = "SELECT * 
          FROM customer_search_view 
          WHERE COALESCE(customer_search_view.first_name,'') LIKE $firstName AND 
            COALESCE(customer_search_view.last_name,'') LIKE $lastName AND 
            COALESCE(customer_search_view.customer_id,'') LIKE $customerId AND 
            COALESCE(customer_search_view.primary_phone,'') LIKE $primaryPhone AND 
            COALESCE(customer_search_view.email,'') LIKE $email AND 
            COALESCE(customer_search_view.store,'') LIKE $store AND 
            COALESCE(customer_search_view.sales_associate,'') LIKE $salesAssociate AND 
            COALESCE(customer_search_view.bdr_associate,'') LIKE $bdrAssociate AND 
            COALESCE(customer_search_view.status,'') LIKE $status AND 
            COALESCE(customer_search_view.lead_category,'') LIKE $leadCategory 
          ORDER BY created_on DESC LIMIT 0,100";

如果无论如何都要搜索LIKE NULL的内容,那么这也是一个快速的解决方案。

查找NULL的唯一方法是使用COALESCE(customer_search_view.primary_phone,'') IS NULL,因此您需要将变量扩展为类似

COALESCE(customer_search_view.primary_phone,'') $primaryPhoneOperator $primaryPhone

如果你不能改变你的前端,你可以在你的查询之前循环通过值,比如

if(empty($primaryPhone)) { $primaryPhoneOperator = "IS NULL";  } else { $primaryPhoneOperator = "LIKE"; }