php - 附加未知数量的 WHERE 参数

标签 php mysql arrays

我正在尝试找到最合乎逻辑(一如既往)的方式来接受查询中的 WHERE 参数列表。我遇到了如何确定它是否是数组末尾的常见问题,我需要添加或不添加另一个“AND”

$params = array(
   array("id","=","1"),
   array("id","!=","2"),
   array("name","=","test"),
)

someQuery($params);

private function someQuery($where = null){
    $this->q = "SELECT stuff FROM table";
    if ($where){
        $this->q .= " WHERE ";
        foreach($where as $x){
           $this->q .= implode(" ", $x);
           if (!notLastElement) $this->q .= " AND ";
        }
    }
}

我似乎建议使用 end()、reset()、slice、带计数器的 for 循环等。但似乎没有人同意一个答案。我相信 end() 不会在我的循环中工作。感谢您的帮助。

最佳答案

它应该像内爆参数数组一样简单,例如 -

private function someQuery($where = null){
    $this->q = "SELECT stuff FROM table";
    if ($where){
        $parameters = array();
        foreach($where as $x){
            $condition = implode(' ', $x); // I'd review this - why are you forming your parameter array the way that you are?
            array_push($parameters, $condition);
        }
        $conditions = implode(' AND ', $parameters);
        $this->q .= ' WHERE ' . $conditions; // only concatenate once
    }
}

关于php - 附加未知数量的 WHERE 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415510/

相关文章:

javascript - 如何将变量传递给我的回调函数或类似函数

php - 需要知道mysqli_connect默认超时

php - 我的 ask.php 语法有什么问题?

php - CakePHP 中的 MySQL 表字段注释而不是名称

php - 将数组和数组中的对象转换为纯数组

c++ - 从 Char 数组中删除前两个字符

javascript - php curl使用html下拉选择填充变量

php - Vicidial 的 MySQL 过滤器

php - 将动态输入字段插入数据库

mysql - 在 MySQL 中存储物理尺寸