1

我有一个 SQL 查询,使用一堆 OR x = y 语句检查表中是否已经存在多个给定值中的一个。然后我对结果进行行数。

$exists = db_query("SELECT * FROM {leads_client} WHERE (companyName = '".$form_state['values']['company_name']."' 
                        OR billingEmail = '".$form_state['values']['billing_email']."' 
                        OR leadEmail = '".$form_state['values']['lead_email']."'
                        OR contactEmail = '".$form_state['values']['contact_email']."'
                        OR url = '".$form_state['values']['company_url']."') AND NOT 
                        clientId = '".$clientId."'");

    if($exists->rowCount() > 0){
          //Do something
    }

在不将其分解为多个查询的情况下,确定哪些 OR 语句是正确的最简洁的方法是什么?

4

3 回答 3

1

您的网站容易受到 SQL 注入攻击。您需要立即阅读本文并修复所有数据库查询以正确使用参数。

Drupal 编写安全代码: https ://drupal.org/writing-secure-code

Drupal 数据库访问: https ://drupal.org/node/101496

于 2013-09-22T03:14:23.390 回答
1

您可以在选择中进行原始比较:

SELECT *, 
    companyName = '".$form_state['values']['company_name']."' AS companyNameMatch,
    billingEmail = '".$form_state['values']['billing_email']."' AS billingEmailMatch,
    ...
FROM {leads_client} 
WHERE (companyName = '".$form_state['values']['company_name']."' 
       OR billingEmail = '".$form_state['values']['billing_email']."' 
       OR leadEmail = '".$form_state['values']['lead_email']."'
       OR contactEmail = '".$form_state['values']['contact_email']."'
       OR url = '".$form_state['values']['company_url']."') AND NOT clientId = '".$clientId."'");

这将返回一个结果集,如:

|------------------|-------------------|
| companyNameMatch | billingEmailMatch |
|------------------|-------------------|
| 0                | 1                 |
|------------------|-------------------|

这样,您将通过带有 1 的列知道哪个匹配。

于 2013-09-22T03:14:32.730 回答
0

您可以添加一条CASE语句来跟踪满足哪个条件,例如:

SELECT *
      ,CASE WHEN companyName = '".$form_state['values']['company_name']."' THEN 'condition1'
            WHEN billingEmail = '".$form_state['values']['billing_email']."' THEN 'condition2'
            ...
       END
FROM {leads_client} 
WHERE (companyName = '".$form_state['values']['company_name']."' 
       OR billingEmail = '".$form_state['values']['billing_email']."' 
       OR leadEmail = '".$form_state['values']['lead_email']."'
       OR contactEmail = '".$form_state['values']['contact_email']."'
       OR url = '".$form_state['values']['company_url']."') AND NOT 
                        clientId = '".$clientId."'");
于 2013-09-22T02:56:02.990 回答