Rawland Hustle Rawland Hustle - 3 days ago 6
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:

http://example.com/getData.php?keyword=a1

I want to be able to handle this scenario:

http://example.com/getData.php?keyword=a1,b1,c1,a2,b2,c2

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?

Thanks!

Answer

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'
Comments