如何使用PHP查询获取结果之间的日期

时间:2016-12-17 09:36:12

标签: php sqlite pdo

我正在尝试根据用户输入的月份和年份以及表名从数据库中获取一些数据。

从月份和年份开始,我计算from_date和to_date 但是如果我在$ from_date和$ todate之间放置日期,则查询无效。

$tableName = $_REQUEST['tableName'];
$month = $_REQUEST['monthName'];
$year = $_REQUEST['yearName'];
// echo json_encode($tableName);
$tableName = json_encode($tableName);
//echo $tableName;

$from_date = date('Y-m-d',strtotime($year."-".$month."-01"));
//echo json_encode($from_date);
//$to_date = date('Y-m-d',strtotime($year."-".$month."-01"));
$to_date = date('Y-m-t', strtotime($from_date));
//echo json_encode($to_date);

$conn = new PDO("sqlite:../../assets/rule_data.db");
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        //$sqlQuery = "select * from $tableName WHERE date >= '".$from_date."' AND date <= '".$to_date."' ";
        //$sqlQuery = "SELECT * FROM $tableName WHERE v_cr_sysdate >= '".$from_date."'  AND  v_cr_sysdate <= '".$to_date."' ";
        //$sqlQuery = "SELECT * FROM $tableName";
        //$sqlQuery = "select * from $tableName WHERE date >= '".convert('$from_date','%d-%m-%y')."' AND date <= '".date($to_date)."' ";
        $sqlQuery = "select * from $tableName WHERE date between '". date('Y-m-d', strtotime($from_date))."' ";
        $sqlQuery .= " AND date <='". date('Y-m-d', strtotime($to_date))."' ";
        $query = $conn->query($sqlQuery);       
        echo json_encode($query);
        echo json_encode(["riskModules"=>$query->fetchAll(PDO::FETCH_ASSOC)]);

如果我删除AND consition并仅保留日期&gt; =&#39; $ from_date&#39;它将起作用,但不适用于日期和日期。

请帮助我在错误的地方给出和查询clasuse。

1 个答案:

答案 0 :(得分:1)

  

您可以使用BETWEEN子句替换“大于”的组合   等于和小于等于“条件。

<强> 更改

$sqlQuery = "select * from $tableName WHERE date between '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND '". date('Y-m-d', strtotime($to_date))."' ";

(OR)

相似
$sqlQuery = "select * from $tableName WHERE date >= '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND date <= '". date('Y-m-d', strtotime($to_date))."' ";

<强> 语法

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

快速链接