在UNION查询中将php数组中的值作为参数传递

时间:2016-02-08 19:46:46

标签: php mysql arrays

我想将数组中的值作为查询中的单个参数传递,并使用它们,如下所示

Array
(
    [0] => some
    [1] => text
)

我想要这种功能

public function getData($some,$text)
{
$sql = " select * from table where field1 = '{$some}' OR field3 = {$some}      ";
$union = " UNION ";
$sql = " select * from table where field2 = '{$text}' or field4 = {$text}  ";
}

注意:数组可能包含第N个索引。

2 个答案:

答案 0 :(得分:0)

由于您的查询是在同一列上进行的,请尝试使用IN运算符跳过UNIONS:

select * from table where field1 IN (val1,val2....)

然后你可以传递一个数组作为参数

public function getData($data)
{
    if(!empty($data)) {
        return " select * from table where field1 = ".implode(",",$data);
    }
}

答案 1 :(得分:0)

您可以使用以下内容:

public function getQuery($dataArray) {
    $queryArray = array();
    foreach($dataArray as $data) {
        $query = "SELECT * from `table`";
        $conditionArray = array();
        foreach($data as $key => $value) {
            $conditionArray[] = "`$key` = `$value`";
        }
        if (!empty ($conditionArray)) {
            $query .= " WHERE ". implode(" OR ", $conditionArray);
        }
        $queryArray[] = $query;
    }
    return implode(" UNION ", $queryArray);
}