2

正如我在标题中解释的那样,我想在我的 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{...}
...

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

4

2 回答 2

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);
于 2013-06-13T12:53:48.377 回答
1

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

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

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

于 2013-06-13T12:47:39.987 回答