Francisco Venes Francisco Venes - 1 year ago 79
HTML Question

SQL SELECT statement from $_POST

I'm trying to build a SQL

statement from information collected through an html form, stored in the
array. My difficulty arises because the statement must vary according to user's inputs.

I have 2 dropdown menus, whose values are stored in
, respectively. So far so good.

Then I've 4 checkboxes for countries and 15 for years. The first stored in the array
and the second in

I've tried to build the SQL statement through foreach loops like this:

//Define SQL SELECT statement
$sql = "SELECT * FROM ".$_POST['tables']." WHERE FlowType = '".$_POST['flow']."' AND (";

foreach ($_POST['country'] as $value) {
$sql .= "Reporter = '$value' OR ";

$sql = substr($sql, 0, -3);
$sql .= ") AND (";

foreach ($_POST['year'] as $value) {
$sql .= "TradeYear = '$value' OR ";

$sql = substr($sql, 0, -4);
$sql .= ")";

echo $sql;

It works, yet I have a feeling it could be implemented differently. Moreover, it will be complicated to apply prepared statements for PDO query with this method.

Any suggestions? I'd appreciate some inputs on this since my knowledge on PHP (and programming in general) is very basic. Thank you!

Answer Source

Ignoring my comment from above, this should work (albeit, totally unsafe):

//Define SQL SELECT statement
$sql = "SELECT * FROM ".$_POST['tables']." WHERE FlowType = '".$_POST['flow'];

if(isset($_POST['country']) && is_array($_POST['country']) && count($_POST['country']) > 0)
    $sql.= " AND Reporter in ('".implode("','", $_POST['country'])."')";

if(isset($_POST['year']) && is_array($_POST['year']) && count($_POST['year']) > 0)
    $sql.= " AND TradeYear in ('".implode("','", $_POST['year'])."')";

echo $sql;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download