有时ajax数据库调用返回空数组


Sometimes ajax database call return empty array?

我想弄清楚为什么有时我的php函数返回一个空数组。触发ajax调用的事件是当下拉菜单被更改时,然后它命中我的php函数。大多数情况下,它会从数据库返回数据,但有时它不会,尽管做了完全相同的事情(更改下拉菜单)。基本上,我使用console.log来检查返回的内容,有时什么都没有。尽管在其他时候使用相同的输入,它工作得很好。

$(document).ready(function() {
$( "#qtrselect" ).change(function() {
    qtrselection = $( "#qtrselect" ).val();
    createQtrTable(qtrselection);
    $('#qtrselect').prop('disabled', true);
    setTimeout(function () {
     $('#qtrselect').prop('disabled', false);
}, 1000);
});    
} );
function createQtrTable(qtrselection, id) {
    $.ajax({
        type : 'POST',
        url  : 'createnewtable.php',
        data : {qtrdate: qtrselection, id: id},
        success :  function(response)
      {   
        response = jQuery.parseJSON(response);
          totalcommision = 0;
          totalpayments = 0;
          for (i = 0; i < response.length; i++) { 
            totalcommision += parseFloat(response[i][0]);
            totalpayments += parseFloat(response[i][3]);
          }
//I've cut out a bit here as it's not really needed to see the problem.
      }
   });
}

createnewtable.php

$qtrdate = $_POST['qtrdate'];
$id = $_POST['id'];
$startdate = '';
$enddate = '';
switch ($qtrdate) {
        case 0:
        $startdate = '2016-01-01' ;
        $enddate = '2018-12-30';
        break;
        case 1:
        $startdate = '2016-08-01' ;
        $enddate = '2016-10-31';     
        break;
        case 2:
        $startdate = '2016-11-01' ;
        $enddate = '2017-01-31';          
        break;
        case 3:
        $startdate = '2017-02-01' ;
        $enddate = '2017-04-30';
        break;
        case 4:
        $startdate = '2017-05-01' ;
        $enddate = '2017-07-31';      
        break;
}
  try
  { 
   $stmt = $db_con->prepare("SELECT com.commisionAmount, stu.studentName, pay.paymentDate, pay.paymentAmount FROM `commisions` as com INNER JOIN `accounts` as acc ON com.commisionAccount = acc.id INNER JOIN `studentpayments` as pay ON com.paymentID = pay.id INNER JOIN `students` as stu ON pay.paymentStudent = stu.id WHERE pay.paymentDate BETWEEN '$startdate' AND '$enddate' AND acc.id = '$id'");
    $stmt->execute();
   $results = $stmt->fetchAll();
  $results = json_encode($results);
      echo $results;
  }
  catch(PDOException $e){
   echo $e->getMessage();
  }

谢谢。

你的id变量在javascript中总是未定义的。

这一行:

createQtrTable(qtrselection);

你需要id

createQtrTable(qtrselection, id);