Francisco Venes Francisco Venes - 3 months ago 16
HTML Question

SQL SELECT statement from $_POST

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!

Answer

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

<?php 
//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;
?>
Comments