PHP sql查询在

时间:2016-12-16 07:23:56

标签: php mysql

我正在尝试根据用户指定的日期处理查询。

所以要形成动态查询我正在编写如下代码但是$ to_date不在这里。如果我删除$ to_date然后它工作正常。请帮忙

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

$sqlQuery = "select * from $tableName WHERE date >= '".$from_date."' AND date <= '".$to_date."'";

如果我将查询更改为仅单个日期然后工作,但AND / BETWEEN / lessa等不工作..任何建议更改日期格式?

 $sqlQuery = "SELECT * FROM $tableName WHERE date ='" . $from_date  

我正在尝试下载数据,所以当在WHERE查询中添加AND部分时,它会给出错误,即输出变量未定义。如果我删除它写入csv文件并执行查询。

完整代码如下

<?php

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

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data1.csv');

try {
    $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 date BETWEEN '2016-03-01' AND  '2016-03-30' ";
        $query = $conn->query($sqlQuery);       
        echo json_encode($query);
        //echo json_encode(["riskModules"=>$query->fetchAll(PDO::FETCH_ASSOC)]);
        $first = true;

        while ($row = $query->fetch(PDO::FETCH_ASSOC))
        {
         // $out = fopen('output.csv', 'a');
         $out = fopen('php://output', 'a');
          if ($first === true) {
            $first = false;
            fputcsv($out, array_keys($row));
        }         
        fputcsv($out, array_values($row));

        }
         fclose($out);

} catch (PDOException $e) {
    echo json_encode([type => "Database exception", error => $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode([type => "General exception", error => $e->getMessage()]);
} 
?>

0 个答案:

没有答案