根据变量的存在创建一个sql查询($ _POST)

时间:2013-06-13 12:40:38

标签: php sql pdo

正如我在标题中解释的那样,我想在我的php页面上创建一个sql查询,以返回存在变量函数的特定结果。 我的页面顶部有一个表单,有一些输入(日期,名称等等),当我点击时,我刷新了正确结果的页面。

目前我的语法是:

if (isset($_POST['dated']) && $_POST['dated'] != null){
    $doleances = $bdd->prepare('SELECT * FROM doleance WHERE Priorite < 5 AND Date >= ? ORDER BY ID DESC');
    $doleances->execute(array($newDate));

}
else if (isset($_POST['dated']) && $_POST['dated'] != null && isset($_POST['datef']) && $_POST['datef'] != null){
    $doleances = $bdd->prepare('SELECT * FROM doleance WHERE Priorite < 5 AND Date BETWEEN ? AND ? ORDER BY ID DESC');
    $doleances->execute(array($newDate, $newDate2));
}
else if{...}
else if{...}
...

但我认为有更好的方法可以做到这一点...... 提前致谢

2 个答案:

答案 0 :(得分:3)

您可以使用“随用随身”方法:

// Create holders for the WHERE clauses and query parameters
$where = array(
  "Priorite < 5"  // this looks common across all queries?
);
$params = array();

// Now build it based on what's suppled:
if (!empty($_POST['dated'])){
  if (!empty($_POST['datef'])){
    // Add to the params list and include a WHERE condition
    $params['startdate'] = $_POST['dated'];
    $params['enddate'] = $_POST['datef'];
    $where[] = "Date BETWEEN :startdate AND :enddate";
  }
  else{
    // Add to the params list and include a WHERE condition
    $params['date'] = $_POST['dated'];
    $where[] = "Date >= :date";
  }
}
else if { ... }
else if { ... }

// Now build and execute the query based on what we compiled together
// from above.
$sql = "SELECT * FROM doleance "
     . (count($where) > 0 ? "WHERE " . implode(" AND ", $where) : "")
     . " ORDER BY ID DESC";
$doleances = $bdd->prepare($sql);
$doleances->execute($params);

答案 1 :(得分:1)

首先创建一个可能发布的变量数组:

$possibleArgs = array( 'dated', 'datef' );

然后遍历每个$possibleArg并检查相应的$_POST[possibleArg]是否为空。如果它不为空,请将其添加到谓词中。