PHP使用AND条件动态创建SQL查询

时间:2014-05-29 10:26:35

标签: php mysql arrays

我正在尝试编写一些适合更大方法的PHP,以便我可以动态创建MySQL查询。

我还没有将代码包含在包含此代码的更大方法中,因为我认为此位的逻辑是自包含的。

所以,我有一个多维数组:

$where=array(array('username', 'pid', 'name'), array('=','<=', '='), array('alex',2,'james'));

当print_r()显示这个结构时:

Array
(
[0] => Array
    (
        [0] => username
        [1] => pid
        [2] => name
    )

[1] => Array
    (
        [0] => =
        [1] => <=
        [2] => =
    )

[2] => Array
    (
        [0] => alex
        [1] => 2
        [2] => james
    )

)

如果使用每个二级数组中的第一个值来构建查询的开头,我想做什么,例如

SELECT * FROM table WHERE username = alex

然后使用其他值来构建查询,例如(取决于数组中的项目数)

SELECT * FROM table WHERE username = alex AND pid <= 2 AND name = james

以下是我编写的代码

 if (is_array($where[0])){
        $i=0;
        $field = $where[0][$i]; 
        $operator = $where[1][$i]; 
        $value= $where[2][$i]; 
        $sql= "SELECT * FROM table WHERE {$field} {$operator} {$value}";
        while($i=0 ) {
            print $sql;
            $i++;
        }
        while($i>0 AND $i< sizeof($where[0]))
        $field = $where[0][$i]; 
        $operator = $where[1][$i]; 
        $value= $where[2][$i]; 
        print $sql .= " AND {$field} {$operator} {$value}";
        $i++;

}

然而,这只打印出一个查询

SELECT * FROM table WHERE username = alex AND username = alex

我正在使用PDO,所以实际上{$ value}被替换为?并绑定在方法的其他地方。我已经在这里完整地展示了它。

2 个答案:

答案 0 :(得分:1)

$sql = 'SELECT * FROM table WHERE';
for($i = 0; $i < count($where[0]); $i++){
    $sql .= " {$where[0][$i]} {$where[1][$i]} {$where[2][$i]} AND";
}
$sql = substr($sql, 0, strlen($sql) - 4);

我个人会保存你的陈述:

$array = array('username = alex', 'pid <= 2');

如果您需要语句的不同部分,则可以执行

explode(' ', $array[num]);

答案 1 :(得分:-1)

$companyFilter = "";
$auth = getFormulaAuth();
$companyFilter = "AND company_id = {$auth['company_id']} ";
$arguments = func_get_args();

if ($WhereFilterName_xxx) {

} else {
    $db = new Database();
    $this_get_table_form = getFormulaFormDetails($FormName);
    $tbfields_data = Formula::getTBFields($this_get_table_form["id"], $db);

    $q_string = "SELECT * FROM `" . $this_get_table_form["form_table_name"] . "`";
    $valid_param_check = count($arguments) - 2;
    $cache_key = "*";

    if ($valid_param_check >= 1 && $valid_param_check % 3 == 0) {
        $found_indexes = array();
        $q_string_where = " WHERE ";
        $search = " (NOT EXISTS(SELECT * FROM tbtrash_bin WHERE record_id = " . $this_get_table_form["form_table_name"] . ".id
                                        AND form_id = " . $this_get_table_form["id"] . "
                                        AND table_name='" . $this_get_table_form["form_table_name"] . "')) AND ";
        $q_string_where .= $search;
        for ($i = 2; $i < count($arguments); $i+=3) {
            $field_key = $arguments[$i];
            $operator = $arguments[$i + 1];
            $value = $arguments[$i + 2];

            if ($i > 2) {
                $q_string_where .= " AND ";
            }
            $q_string_where .= " `" . $field_key . "` " . $operator;

            if (($tbfields_data["" . $field_key]["field_input_type"] == "Number" || $tbfields_data["" . $field_key]["field_input_type"] == "Currency") || strtoupper($operator) == "IN") {
                $q_string_where .= " " . $value . " ";
            } else {
                $q_string_where .= " '" . $value . "' ";
            }

        $q_string_orderby .= $q_string_where;
        $sort_by = isset($_GET['s']) ? $_GET['s'] : false;

            switch ($sort_by) {
                case $tbfields_data;
                    break;
                default:
                    $sort_by = 'DateCreated';
            }

        $q_string_orderby .= ' ORDER BY '.$sort_by.' ';

        $direction = isset($_GET['d']) ? $_GET['d'] : false;
            if ($direction != 'ASC' && $direction != 'DESC')
                $direction = 'DESC';
            $q_string_orderby .= $direction;

        $res = $db->query($q_string_orderby);
        $results = array();
        if ($res) {
            while ($r = mysql_fetch_assoc($res)) {
                $results[] = $r;
            }
        }

            $cache_key.="::" . $field_key . "::" . $operator . "::" . $value . "::" . $q_string_orderby;
        }

        $q_string .= $q_string_orderby;
    }

    $this_record = Formula::getLookupValue("formula_lookup_where_array", $this_get_table_form, $q_string, $cache_key);
    array_push($GLOBALS['formula_executed_data_collector']['collected_form_id'], array(
        "form_id" => $this_get_table_form['id'],
        "where" => $q_string_where,
        "function_name" => "Total",
        "whole_query" => $q_string
    ));

    $rslt = array_values(array_map(function($a) use($ReturnField) {
                if (gettype($ReturnField) == "array") {
                    $array_collector = array();
                    foreach ($ReturnField as $key => $value) {
                        $array_collector[$value] = $a[$value];
                    }
                    return $array_collector;
                } else if ($ReturnField == "*") {
                    return $a;
                } else {
                    return $a[$ReturnField];
                }
            }, $this_record));
    return $rslt;
}

}