I'm trying to build a SQL SELECT
statement from information collected through an html form, stored in the $_POST
array. My difficulty arises because the statement must vary according to user's inputs.
I have 2 dropdown menus, whose values are stored in $_POST['flow']
and $_POST['tables']
, respectively. So far so good.
Then I've 4 checkboxes for countries and 15 for years. The first stored in the array $_POST['country']
and the second in $_POST['year']
.
I've tried to build the SQL statement through foreach loops like this:
<?php
//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!