簡體   English   中英

追加未知數量的WHERE參數

[英]Appending an unknown amount of WHERE parameters

我正在嘗試找到最合理(一如既往)的方式來接受查詢中的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,帶計數器的循環等提出了建議。但是似乎沒人同意一個答案。 我相信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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM