【问题标题】:Create a sql query based on the existence of variables ($_POST)根据变量的存在创建一个sql查询($_POST)
【发布时间】:2013-06-13 12:40:37
【问题描述】:

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

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

【问题讨论】:

标签: php sql pdo


【解决方案1】:

您可以使用即用即构建的方法:

// 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);

【讨论】:

  • 我也有同样的想法,我不确定有没有比这更好的方法。旁注:isset()!empty() is redundant 的使用,只需使用!empty()
  • @billyonecan:很高兴知道。自从我进入 PHP 领域以来已经有一段时间了,但总是很高兴知道更好的方法。谢谢!
【解决方案2】:

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

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

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

【讨论】:

  • 唯一的问题是当需要检查多个变量作为条件的一部分时
  • @billyonecan 也为此构建一个数组。
  • @billyonecan 谁知道呢。我不会让我的干草叉超过 -2 代表。
猜你喜欢
  • 2019-07-31
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
相关资源
最近更新 更多