简体   繁体   English

$ _POST中的SQL SELECT语句

[英]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. 我正在尝试通过存储在$_POST数组中的html表单收集的信息来构建SQL SELECT语句。 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. 我有2个下拉菜单,其值分别存储在$_POST['flow']$_POST['tables'] So far so good. 到现在为止还挺好。

Then I've 4 checkboxes for countries and 15 for years. 然后,我有4个用于国家/地区的复选框,以及15个/年的复选框。 The first stored in the array $_POST['country'] and the second in $_POST['year'] . 第一个存储在数组$_POST['country'] ,第二个存储在$_POST['year']

I've tried to build the SQL statement through foreach loops like this: 我试图通过如下的foreach循环构建SQL语句:

<?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. 而且,使用这种方法将准备好的语句应用于PDO查询将很复杂。

Any suggestions? 有什么建议么? I'd appreciate some inputs on this since my knowledge on PHP (and programming in general) is very basic. 我希望对此有所投入,因为我对PHP(以及一般编程)的知识非常基础。 Thank you! 谢谢!

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;
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM