在php中动态sql搜索

时间:2015-06-06 11:13:59

标签: php mysql

尝试创建动态搜索功能。

目标:允许用户通过电子邮件(如果不是空)进行搜索,如果为空(按姓氏),如果两者都不为空,则为两者等。

我知道我可以编写描述每个场景的语句,而不是基于此插入SQL命令,问题是可以以更简化的方式处理。谢谢你的帮助。

当前功能设置在所有字段中都是OR,值来自$ _POST:

find_transaction($email,$last_name,$first_name, $transaction_id) 
{
    GLOBAL $connection;

    $query  = "SELECT * ";
    $query .= "FROM transactions WHERE ";
    $query .= "email='{$email}' ";
    $query .= "OR last_name='{$last_name}' ";
    $query .= "OR first_name='{$first_name}' ";
    $query .= "OR transaction_id='{$transaction_id}' ";
    $query .= "ORDER BY date DESC";
    $email = mysqli_query($connection,$query);

    confirm_query($email);
    return $email;

} 

2 个答案:

答案 0 :(得分:0)

我一直这样做,这不是太多的工作。基本上使用一系列if语句基于POST变量动态构建WHERE语句。

例如:

$where_statement = "";

// First variable so is simpler check.
if($email != ""){
    $where_statement = "WHERE email = '{$email}'";
}


// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
    if($where_statement == ""){
        $where_statement = "WHERE last_name = '{$last_name}'";
    }else{
        $where_statement .= " OR last_name = '{$last_name}'";
    }
}

// Repeat previous 'last_name' check for each remain variable.

SQL语句将更改为:

$query = "SELECT * FROM transactions
              $where_statement
              ORDER BY date DESC";

现在,SQL将只包含过滤器,具体取决于存在的值,因此有人只是输入电子邮件,它会生成:

$query = "SELECT * FROM transactions
              WHERE email = 'smith@email.com'
              ORDER BY date DESC";

如果他们输入姓氏,则会生成:

$query = "SELECT * FROM transactions
              WHERE last_name = 'Smith'
              ORDER BY date DESC";

如果他们同时放两个,就会生成:

$query = "SELECT * FROM transactions
              WHERE email = 'email@email.com' OR last_name = 'Smith'
              ORDER BY date DESC";

等等。

你可以在这里添加你想要的变量,基本上如果特定变量不是空白,它会将它添加到“$ where_statement”,并且取决于“$ where_statement”中是否还有任何变量,它将决定以=“WHERE”开头,或追加。=“​​或”(注意'。='和'OR'之前的空格。

答案 1 :(得分:-1)

更好地使用数据交互表:http://datatables.net/

这很有用,没有SQL注入:)祝你好运!