简体   繁体   English

查询数据库,其中Where子句取决于数组值

[英]Query Database with Where Clause depending on array values

You must have seen this in WordPress, how you pass arguments to function and it queries the database depending on the arguments you have passed. 您一定已经在WordPress中了解了如何将参数传递给函数,以及如何根据传递的参数查询数据库。 If the arguments are not passed. 如果未传递参数。 It will nautically fall back to the default arguments. 它将自然退回到默认参数。 Exactly same thing I want to do here in my custom function. 我想在我的自定义函数中做同样的事情。

 function get_module( $args = NULL ){
    $defaults = array(
        "module_id" => NULL,
        "module_slug" => NULL,
        "module_parent" => NULL,
        "module_status" => "publish"
    );
    global $db;
    global $table_prefix;
    $sql = "SELECT * FROM $table_prefix" . "modules";
    $query = $db->SELECT($sql);
    return $db->FETCH_OBJECT();
}

Ok, so lets do this step-by-step. 好的,让我们逐步进行。

If the arguments are not passed. 如果未传递参数。 It will nautically fall back to the default arguments 它将自然退回到默认参数

You already have a $defaults array, now the question is how to get it "together" with $args - the solution is using array_merge() . 您已经有一个$defaults数组,现在的问题是如何与$args “一起”获得它-解决方案是使用array_merge() If you do merge $args and $defaults , you need to watch out that $args ' elements override $defaults - not the other way round. 如果合并$args$defaults ,则需要注意$args的元素会覆盖$defaults ,而不是相反。 ( fiddle ) 小提琴

$options = array_merge($defaults, $args) // good
$options = array_merge($args, $defaults) // bad

Now the question is: Do you want to query the database for entries where the value is NULL ? 现在的问题是:您是否要在数据库中查询值为NULL条目? I don't think so, array_filter() comes in handy now to delete those elements not needed. 我不这么认为, array_filter()现在很方便删除不需要的元素。 This little snippet should already do the trick: 这个小片段应该已经可以解决问题了:

function notNull($value) {
    return $value !== NULL;
}
$options = array_filter($options, "notNull");

Now you have an array $options which should be used in the query. 现在,您有一个数组$options应该在查询中使用。 To do so you need to loop over the array, as you need both key and value for each item. 为此,您需要遍历数组,因为每个项目都需要键和值。 While doing this you can already build your WHERE part. 在执行此操作时,您已经可以构建WHERE部分。

$where = "";
if (count($options) > 0) {
    foreach ($options as $key=>$value) {
        if (!empty($where))
            $where .= " AND ";
        else
            $where = " WHERE ";

        $where .= sprintf("`%s` = `%s`", $key, $value);
    }
}

This will automatically convert values to string due to sprintf() , you can add additional checks (numeric values should not be quoted in MySQL I believe). 由于sprintf() ,这将自动将值转换为字符串,您可以添加其他检查(我相信MySQL中不应引用数字值)。


You could also use a prepared statement which will be created in the loop and set the values afterwards. 您也可以使用准备好的语句,该语句将在循环中创建并随后设置值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM