vivek.sharma February 2016

Pass values from php array as param in UNION query

I want to pass values from array as individual parameter in a query and use them as below

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

I want this kind of function

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}  ";
}

Note: The array may have Nth number of index.

Answers


KA_lin February 2016

Since your query is made on the same column, try the IN operator to skip UNIONS:

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

Then you can pass an array as the parameter

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


Akshat Singhal February 2016

You can use the following:

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);
}

Post Status

Asked in February 2016
Viewed 3,480 times
Voted 10
Answered 2 times

Search




Leave an answer