Rawland Hustle Rawland Hustle - 1 year ago 80
SQL Question

Construct SQL SELECT query out of multiple PHP GET parameters

I'm using the code provided in answer http://stackoverflow.com/a/5203351/1711950 to handle different combinations of SQL WHERE clauses:

$vars = array(
(!empty($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(!empty($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(!empty($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(!empty($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null

function myfilterarray($var)
return !empty($var)?$var: null;

$newvars = array_filter($vars, 'myfilterarray');

$where = join(" OR ", $newvars);

$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);

echo $sql;

The code works when each GET parameter is a single value like this:


I want to be able to handle this scenario:


Therefor I've modified the code like this:

(!empty($_GET["var1"]))? " keyword IN ('". $_GET["var1"] ."') ": null

That off course makes the SQL query look like this,
which won't work because of the quotations.

SELECT * FROM table WHERE keyword IN ('SE162321000156-3PQZ,SE2321000164-7381037592311')

How could I get around this problem?


Answer Source

You have to split the values , put quotation marks around them and concatenate the string back together. This is a very very basic example:

$foo = (!empty($_GET["keyword"]))? $_GET["keyword"] : null;
$foo = explode(",", $foo);
$fooArray = [];
foreach( $foo as $fooElement ) {
    $fooArray[] = "'$fooElement'";
$foo = implode(",", $fooArray);

echo $foo; // output: 'a1','b1','c1','a2','b2','c2'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download