SQL查询上的PHP AJAX日期时间范围问题


PHP AJAX datetime range probleme on SQL Query

我有一个大问题,希望能在这里找到解决方案。经过4天无用的搜索,我来到这里寻求解决方案。

这是我的问题。我使用SQL Server数据库和php作为服务器端语言,并使用AJAX将params发送到php服务器。

如果用户输入某个日期范围,我的web应用程序必须显示一些数据的列表。

这里是我的html表单代码:

<form method="post" action="">
    <input type="text" placeholder="Start date : dd/mm/yyyy" id="date1" name="date1">
    <input type="text" placeholder="Date de fin : dd/mm/yyy" id="date2" name="date2">
    <input type="BUTTON" class="my-button" value="Show Data" onClick="LoadData()">
</form>

这是我的javascript函数LoadData()

<script>
function LoadData(){
    var url = "json.php";
        var date1=document.getElementById('date1');
        var date2=document.getElementById('date2');
        var xmlhttp = new XMLHttpRequest();
        var params= 'date1=' + date1 + '&date2=' + date2 ;
        xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
                        }
                    }
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(params);

        function myFunction(response) {
        var arr = JSON.parse(response);
        var i; 
        var sum = 0;
        var out = "";               
        for(i = 0; i < arr.length; i++) 
        out += '<li><div class="news_desc"><table width="100%" border="1"><tr><td width="70%"><h4><a>' + 
                            arr[i].Name +
                            '</h4></td><td width="30%">' +
                            arr[i].Price +
                            '</td></tr><tr><td><p>' +
                            arr[i].Date +
                            '</p></td><td>&nbsp;</td></tr></table></div><div class="clear"> </div></li>' ;
                        }
        out += ''
        document.getElementById("id01").innerHTML = out;
    }
        }
</script>

这是我的php脚本

if(isset($_POST['date1']) && isset($_POST['date2']) )
{
    $date1 = $_POST["date1"];
    $date2 = $_POST["date2"];
        $db_name  = "DATABASE";
        $hostname = 'IO-SD-L1';
        $username = '';
        $password = '';
       // connect to the database
        $dbh = new PDO( "sqlsrv:Server= $hostname ; Database = $db_name ", $username, $password);
        $sql = "SELECT name, CAST( DateReg AS DATE ) AS dateIn, price FROM TBL_USERS
                WHERE CAST( DateReg AS DATE )BETWEEN '".$date1."'AND '".$date2."'";
     // the DateReg is datetime type
        $stmt = $dbh->prepare( $sql );
        $stmt->execute();
        $result = $stmt->fetchAll( PDO::FETCH_ASSOC );
        foreach ($result as $row){
        $return[]=array('Name'=>$row['name'],
                    'Date'=>$row['dateIn'],
                    'Price'=>$row['price']);
}
$dbh = null;
echo json_encode($return); } 

如果我像date1="12/12/2011" ; date2="11/12/2014"一样直接将日期范围放在代码中,它非常有效,但如果我通过用户在两个日期文本字段中输入并单击"显示数据"按钮来选择日期范围,我将一无所获。

所以你说当你输入一个日期(硬编码)时,它可以完美地工作;但当您通过文本框控件输入相同的日期时;它不起作用?如果是这样的话,我会这样做:console.log(params)在您获得输入数据之后。你会发现它和你想象的不一样;我怀疑。

如果您希望使用jQuery(因为它简化了xmlhttp处理程序…请这样尝试:

var  formData = "name=johndoe&age=24";  // name value pair
// or...
var formData = { name : "johndoe", age : "24" }; // object
$.ajax({
    url : "/your/url/goes/here.php",
    type: "POST",
    data : formData,
    // if you wish to send the object as JSON, you will need to do this instead of the above...
    // data: JSON.stringify(formData),
    // you will also need to uncomment the next line
    // contentType: "application/json; charset=utf-8",
    success: function(data, textStatus, jqXHR)
    {
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        console.log(errorThrown);
    }
});

参考。AJAX请求中的内容类型和数据类型是什么?

我认为单击按钮时没有调用您的函数。

检查一下,只需添加

alert('check');

我在函数体中的第一行。

托盘也将onClick="LoadData()"更改为onClick="LoadData"

如果您的DATE包含TIME信息,例如11/12/2014 13:30。这将在条款BETWEEN 10/12/2014 AND 11/12/2014中失败(使用英国dd/mm/yyyy格式)。您必须去掉时间部分,使BETWEEN以您需要的方式工作到这里

My LoadData()

 <script>
function LoadData(){
    var url = "json.php?";
    var date1=document.getElementById('date1');
    var date2=document.getElementById('date2');
    var xmlhttp = new XMLHttpRequest();
    var params= 'date1=' + date1 + '&date2=' + date2 ;
         xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                myFunction(xmlhttp.responseText);
                }
            }

            xmlhttp.open("GET", url+params, true);
            xmlhttp.send(null); 
    function myFunction(response) {
    var arr = JSON.parse(response);
    var i; 
    var sum = 0;
    var out = "";               
    for(i = 0; i < arr.length; i++) 
    out += '<li><div class="news_desc"><table width="100%" border="1"><tr><td width="70%"><h4><a>' + 
                        arr[i].Name +
                        '</h4></td><td width="30%">' +
                        arr[i].Price +
                        '</td></tr><tr><td><p>' +
                        arr[i].Date +
                        '</p></td><td>&nbsp;</td></tr></table></div><div class="clear"> </div></li>' ;
                    }
    out += ''
    document.getElementById("id01").innerHTML = out;
}
    }

我的博士代码

if(isset($_GET['date1']) && isset($_GET['date2']) )
{

$date1 = $_GET["date1"];
$date2 = $_GET["date2"];
$start_date = new DateTime($date1);
$end_date = new DateTime($date2);
$start_date = $start_date->format('Y-m-d'TH:i:s');
$end_date= $end_date->format('Y-m-d'TH:i:s');
    $db_name  = "DATABASE";
    $hostname = 'IO-SD-L1';
    $username = '';
    $password = '';
   // connect to the database
    $dbh = new PDO( "sqlsrv:Server= $hostname ; Database = $db_name ", $username, $password);
    $sql = "SELECT name, CAST( DateReg AS DATE ) AS dateIn, price FROM TBL_USERS
            WHERE CAST( DateReg AS DATE )BETWEEN '".$start_date."'AND '".$end_date."'";
 // the DateReg is datetime type
    $stmt = $dbh->prepare( $sql );
    $stmt->execute();
    $result = $stmt->fetchAll( PDO::FETCH_ASSOC );
    foreach ($result as $row){
    $return[]=array('Name'=>$row['name'],
                'Date'=>$row['dateIn'],
                'Price'=>$row['price']);
}
$dbh = null;
echo json_encode($return); }

我希望这将对未来中的某个人有所帮助

I recorded data on the table.  when i execute no errorsand no result.
My customers order table here is below
create table customer_orders 
(
order_date timestamp,
order_id int(10) not null primary key,
customer_id int(10),
due_amount int(100),
invoice_no int(100),
qty int(10),
size text,
order_status text 
)
Here is below my my_orders.php source code
<?php
include("includes/db_connection.php");
 ?>
<body style="margin:20px auto"> 
<center><!--center Starts-->
  <h1 class="row header" style="text-align:center;color:green"> My Orders </h1>
  <p class="lead" style="text-align:center;color:green"> your orders on one place. </p>
  <p class="text-muted"> If you have any questions, please feel free to <a href="../contact.php" > Contact Us, </a> our customer service center is working for you 8/5.</p>
  
</center><!--center Ends-->
<hr>
<form class="form-inline"><!--form-inline Starts-->
<div class="col-md-3 input-group " ><!--col-md-3 Starts-->
  
  <input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date">
  <label class="input-group-addon btn" for="from_date">
       <span class="fa fa-calendar"></span>
</label>
</div><!--col-md-3 Ends-->
<div class="col-md-3 input-group"><!--col-md-3 Starts-->
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date ">
<label class="input-group-addon btn" for="to_date">
       <span class="fa fa-calendar"></span>
</label>
</div><!--col-md-3 Ends-->
<div class="col-md-5 input-group"><!--col-md-5 Starts-->
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-primary btn-md" >
</div><!--col-md-5 Ends-->
<div style="clear:both"></div>
</form><!--form-inline Ends-->
<hr>
<div class="table-responsive" ><!--table-responsive Starts-->
  <table class="table  table-bordered table-hover" id="my_orders" ><!--table  table-bordered table-hover Starts-->
    <thead><!--thead Starts-->
    <tr>
      
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">ON </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Invoice No </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Qty </th> 
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">ETB </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Order Date </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Status </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Assigned</th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">  Wait me for </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-right: 2px; padding-top: 10px; padding-bottom: 10px; "> Satisfied </th>
      
    </tr>
    </thead><!--thead Ends-->
    
 <tbody><!--tbody Starts-->
      <?php
      $customer_session = $_SESSION['customer_username'];
      $get_customer = "select * from customers where customer_username='$customer_session'";
      $run_customer = mysqli_query($con,$get_customer);
      $row_customer = mysqli_fetch_array($run_customer);
      $customer_id = $row_customer['customer_id'];
      $get_orders = "SELECT * FROM customer_orders WHERE customer_id='$customer_id' ORDER BY order_date ASC";
      $run_orders = mysqli_query($con,$get_orders);
      if( mysqli_num_rows($run_orders) > 0)
    {
      $i = 0;
      $total = 0;
    
    while ( $row_orders = mysqli_fetch_array($run_orders)) {
      $order_id = $row_orders['order_id'];
        $due_amount = $row_orders['due_amount'];
        $invoice_no = $row_orders['invoice_no'];
        $qty = $row_orders['qty'];
        $size = $row_orders['size'];
        $date = substr($row_orders['order_date'],0, 11);
        $order_date = date('d-m-Y', strtotime($date));
        $order_status = $row_orders['order_status'];
        $i++;
        $total += $due_amount;
        if($order_status=='pending'){
          $order_status = "Pending";
        }
        elseif($order_status=='Accepted'){
          $order_status = "Approve";
        }
        else {
          $order_status = "Rejected";
        }
       echo '<tr> <td style="text-align: center">  '.$i.'</td>
              <td>  '.$invoice_no.'</td>
              <td style="text-align: center"> '.$qty.'</td>
              <td style="text-align: center">  '.$due_amount.'</td>
              <td> '.$order_date.'</td>
              <td>  '.$order_status.'</td>
              <td>  Seyoum </td>
              <td style="text-align: center"> 30  </td>
              <td>  <select name="satisfied" width="5" height="16" padding-left="0" padding-right="0">
              <option> Yes </option>
              <option> 50% </option>
              <option> No </option>
              </select> <a href="order.php?customer_id=<?php echo $customer_id; ?>" class="btn btn-primary btn btn-xs" > Send</a></td>
          </tr><!--tr Ends-->';
}
}
    else {
      $output .= '
      <tr>
      <td colspan="5" > No order found </td>
      </tr>
      ';
    }
      ?>
      
    </tbody><!--tbody Ends-->
    <tfoot><!-- tfoot Starts-->
                <tr >
                  <th colspan="6" style="text-align: center;font-size: 12px; font-weight: bold; border: 1px solid #999999; border-radius: 0px;" class="alert alert-success " >My Total Orders and Costs Summary  </th>
                  <th colspan="3" style="font-size: 12px; font-weight: bold;  border-left: 0px; border-top: 1px solid #999999; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-success " >My Satisfied Status on Services That I Got </th> 
            
                </tr>
                <tr>
                  <th colspan="3" class="alert alert-info" style="text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-left: 1px solid #999999; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> My Total Orders in Qty  </th>
                  
                  <th colspan="3" class="alert alert-info"style="text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> My Orders Total Costs in ETB </th>
                  <th colspan="1" class="alert alert-info" style="text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> Satisfied  </th> 
                  <th colspan="1" class="alert alert-info" style="text-align: center;font-size: 13px; font-weight: bold;
                   border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> Half(50%) </th>
                  <th colspan="1" style="text-align: center; font-size: 13px; font-weight: bold; border-top: none; border-left: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-info" > Unsatisfied </th>  
                              
                </tr>
                <tr>

                  <th colspan="3" style="text-align: center; ext-align: center;font-size: 13px; font-weight: bold; border-top: none; border-left: 1px solid #999999; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo $i; ?> </th>
                  <th colspan="3" style="text-align: center; font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" > <?php  echo  $total; ?></th>
                  <th colspan="1" style="text-align: center;text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo ""; ?> </th>  
                  <th colspan="1" style="text-align: center; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo "" ;?> </th> 
                  <th colspan="1" style="text-align: center; border-top: none; border-left: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo "" ;?> </th> 
                </tr>
                            
              </tfoot><!-- tfoot Ends-->
  </table><!--table  table-bordered table-hover Ends-->
</div><!--table-responsive Ends-->
</body> 
<script>
$(document).ready(function(){
    $('#my_orders').dataTable();
    $.datepicker.setDefaults({
     dateFormat:'dd-mm-yy'
     });
  
    $(function (){
    $('#from_date').datepicker(); 
    $('#to_date').datepicker();
});
    $('#filter').click(function(){
      var from_date = $('#from_date').val();
      var to_date = $('#to_date').val();
      if(from_date != '' && to_date != '')
      {
        $.ajax({
          url:"filter.php",
          method:"POST",
          data:{from_date:from_date, to_date:to_date},
          success:function(data) {
            $('#my_orders').html(data);
            
          }
        });
      }
      else {
        alert("Please select date")
      }
    });
   
});
</script>
Here is below my filter.php source code
<?php
session_start();
include("includes/db_connection.php");
 ?>
<!DOCTYPE html>
<html>
<head>
<title> OISRMS | Online ICT Support Request Management System </title>
<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css">
</head> 
<body>
<div class="table-responsive" ><!--table-responsive Starts-->
  <table class="table  table-bordered table-hover"><!--table  table-bordered table-hover Starts-->
    <thead><!--thead Starts-->
    <tr>
      
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">ON </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Invoice No </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Qty </th> 
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">ETB </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Order Date </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Status </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">Assigned</th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-top: 10px; padding-bottom: 10px;">  Wait me for </th>
      <th style="text-align: left; font-size: 12px; font-weight: bold; padding-left: 2px; padding-right: 2px; padding-top: 10px; padding-bottom: 10px; "> Satisfied </th>
      
    </tr>
    </thead><!--thead Ends-->
    
 <tbody><!--tbody Starts-->
      <?php
  	if(isset($_POST["from_date"], $_POST["to_date"])) {
    $customer_session = $_SESSION['customer_username'];
    $get_customer = "select * from customers where customer_username='$customer_session'";
    $run_customer = mysqli_query($con,$get_customer);
    $row_customer = mysqli_fetch_array($run_customer);
      $customer_id = $row_customer['customer_id'];
      $get_orders = "SELECT * FROM customer_orders WHERE customer_id='$customer_id' AND order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."' ";
      $run_orders = mysqli_query($con,$get_orders);
    $i = 0;
    $total = 0;
      if( mysqli_num_rows($run_orders) > 0)
    {
    while ( $row_orders = mysqli_fetch_array($run_orders)) {
      $order_id = $row_orders['order_id'];
        $due_amount = $row_orders['due_amount'];
        $invoice_no = $row_orders['invoice_no'];
        $qty = $row_orders['qty'];
        $size = $row_orders['size'];
        $date = substr($row_orders['order_date'],0, 11);
        $order_date = date("d-m-Y", strtotime($date));
        $order_status = $row_orders['order_status'];
        $i++;
        $total += $due_amount;
        if($order_status=='pending'){
          $order_status = "Pending";
        }
        elseif($order_status=='Accepted'){
          $order_status = "Approve";
        }
        else {
          $order_status = "Rejected";
        }
       echo '<tr> <td style="text-align: center">  '.$i.'</td>
              <td>  '.$invoice_no.'</td>
              <td style="text-align: center"> '.$qty.'</td>
              <td style="text-align: center">  '.$due_amount.'</td>
              <td> '.$order_date.'</td>
              <td>  '.$order_status.'</td>
              <td>  Seyoum </td>
              <td style="text-align: center"> 30  </td>
              <td>  <select name="satisfied" width="5" height="16" padding-left="0" padding-right="0">
              <option> Yes </option>
              <option> 50% </option>
              <option> No </option>
              </select> <a href="order.php?customer_id=<?php echo $customer_id; ?>" class="btn btn-primary btn btn-xs" > Send</a></td>
          </tr><!--tr Ends-->';
}
}
    else {
      echo '
      <tr>
      <td style "text-align: center;" colspan="9" > No order found </td>
      </tr>
      ';
    }
}
      ?>
      
    </tbody><!--tbody Ends-->
    <tfoot><!-- tfoot Starts-->
                <tr >
                  <th colspan="6" style="text-align: center;font-size: 12px; font-weight: bold; border: 1px solid #999999; border-radius: 0px;" class="alert alert-success " >My Total Orders and Costs Summary  </th>
                  <th colspan="3" style="font-size: 12px; font-weight: bold;  border-left: 0px; border-top: 1px solid #999999; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-success " >My Satisfied Status on Services That I Got </th> 
            
                </tr>
                <tr>
                  <th colspan="3" class="alert alert-info" style="text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-left: 1px solid #999999; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> My Total Orders in Qty  </th>
                  
                  <th colspan="3" class="alert alert-info"style="text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> My Orders Total Costs in ETB </th>
                  <th colspan="1" class="alert alert-info" style="text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> Satisfied  </th> 
                  <th colspan="1" class="alert alert-info" style="text-align: center;font-size: 13px; font-weight: bold;
                   border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;"> Half(50%) </th>
                  <th colspan="1" style="text-align: center; font-size: 13px; font-weight: bold; border-top: none; border-left: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-info" > Unsatisfied </th>  
                              
                </tr>
                <tr>

                  <th colspan="3" style="text-align: center; ext-align: center;font-size: 13px; font-weight: bold; border-top: none; border-left: 1px solid #999999; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo $i; ?> </th>
                  <th colspan="3" style="text-align: center; font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" > <?php  echo  $total; ?></th>
                  <th colspan="1" style="text-align: center;text-align: center;font-size: 13px; font-weight: bold; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo ""; ?> </th>  
                  <th colspan="1" style="text-align: center; border-top: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo "" ;?> </th> 
                  <th colspan="1" style="text-align: center; border-top: none; border-left: none; border-bottom: 1px solid #999999; border-right: 1px solid #999999; border-radius: 0px;" class="alert alert-warning" ><?php  echo "" ;?> </th> 
                </tr>
                            
              </tfoot><!-- tfoot Ends-->
  </table><!--table  table-bordered table-hover Ends-->
</div><!--table-responsive Ends-->
</body>
</html>