0

I want to display records from mysql-database on a monitor using a table from dataTables with serverside paging. Maximum rows per side should be 14. When filling up the database and reaching the 14th row the table already starts paging (!) showing the message "no matching records found".... then it switches back to the page with 1-14 rows....

Any clue what I am doing wrong here?

My code is as follows:

php-page creating json array

//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=eflightbook", "root", "");
$column = array("usersName", "usersFirstname", "fldirector");
$query = "SELECT usersName, usersFirstname, TIME(date), fldirector, t1.*
FROM users, flightbook t1
WHERE usersLoginStatus <> 'false'
AND id = anw_id
AND t1.date = (SELECT MAX(t2.date)
                FROM users, flightbook t2
                WHERE t2.anw_id = t1.anw_id)

";

if(isset($_POST['order']))
{
    $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY TIME(date) ASC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
    $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$result = $connect->query($query . $query1);
$data = array();
foreach($result as $row)
{
    $sub_array = array();
    $sub_array[] = $row['usersName'];
    $sub_array[] = $row['usersFirstname'];
    $sub_array[] = $row['TIME(date)'];
    $sub_array[] = ($row['fldirector'] == "1") ? "✔" : "";
    $data[] = $sub_array;
}
function count_all_data($connect)
{
    $query = "SELECT anw_id, usersName, usersFirstname, TIME(date), fldirector, t1.*
    FROM users, flightbook t1
    WHERE usersLoginStatus <> 'false'
    AND id = anw_id
    AND t1.date = (SELECT MAX(t2.date)
                    FROM users, flightbook t2
                    WHERE t2.anw_id = t1.anw_id)
    
    ";
    $statement = $connect->prepare($query);
    $statement->execute();
    return $statement->rowCount();
}
$output = array(
    "draw"      =>  intval($_POST["draw"]),
    "recordsTotal"  =>  count_all_data($connect),
    "recordsFiltered"   =>  $number_filter_row,
    "data"      =>  $data
);
echo json_encode($output);
?>


**Monitor html/php Page**
  

<script>

// Active Pilots Table 

$(document).ready(function(){
    function load_data(start, length)
    {
        var dataTable = $('#datatable').DataTable({
            "processing" : false,
            "serverSide" : true,
            "pageLength" : 14,
            "lenghtChange" : false,
            "language": {
             "emptyTable": "** kein Eintrag **"},
             "columnDefs": [
                       {
                        targets: -1,
                        className: 'dt-body-center'
                       }],
            "responsive" : false,
            "autoWidth" : false,
            "ordering" : false,
            "searching" : false,
            "scrollCollapse" : true,
            "binfo" : false,
            "bFilter" : false,
            "bLengthChange" : false,
            dom: "lfrti",
            "order" : [],
           "retrieve": true,
            "ajax" : {
                url:"activep.php",
                method:"POST",
                data:{start:start, length:length}
            },
            "drawCallback" : function(settings){
                var page_info = dataTable.page.info();

                console.log(page_info);
             
            }
        });
    }
    load_data();


    var table = $('#datatable').DataTable();

    setInterval(function(){ 

    var info = table.page.info();

    if (info.start < info.end) {
        var page_number = (info.page < info.pages) ? info.page + 1 : 1; 
    }
    else {
        page_number = 0;
     
    }
    ;

    table.page(page_number).draw(false); 

}, 6000);

});
Dharman
  • 30,962
  • 25
  • 85
  • 135
marcvienna
  • 13
  • 3
  • How many records do you have in the database, more than 14? – K Scandrett Jan 31 '23 at 21:59
  • @KScandrett The rows in the query can be more than 14 or less - in my example above just 14 rows; same effect when rows are decreasing from say 16 to 14 - second page is shown with no entries. – marcvienna Jan 31 '23 at 22:04
  • Your example has paging set at 14, so I'd like to know if there are currently more than 14 records in your DB? – K Scandrett Jan 31 '23 at 22:17
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jan 31 '23 at 22:19
  • @KScandrett As described above in my post there are 14 entries in the database and so there only should be one page with 14 rows without paging to another empty page - in fact paging switches to the second page, which is empty (the 14 entries are already shown on the first page); – marcvienna Jan 31 '23 at 23:59
  • Side note, this is a typo: `lenghtChange` – devlin carnate Feb 01 '23 at 00:03
  • @devlincarnate info.pages is always 1 and info.page is 0 on the first tableview and 1 on the second which is empty... – marcvienna Feb 01 '23 at 00:17
  • @marcvienna : info.pages is the total number of pages, so 1 makes sense. info.page is the current page, and that property is indexed at 0. so the first page is 0. but in your code, you are setting it to 1. see my answer below. – devlin carnate Feb 01 '23 at 00:35

1 Answers1

0

Your problem is here:

var info = table.page.info();

if (info.start < info.end) {
    var page_number = (info.page < info.pages) ? info.page + 1 : 1; 
}
else {
    page_number = 0;
 
}
;

table.page(page_number).draw(false);

There are two issues. First, to specifically answer your question: assuming info.page is equal to info.pages (which means you have one page of records) you are setting the page number to 1, but that property is indexed at 0 (and also documentation here), so you are actually forcing it to the second page:

var page_number = (info.page < info.pages) ? info.page + 1 : 1;

and then later, you pass that page number value to your table:

table.page(page_number).draw(false);

And the second issue (which is not the cause of your specific problem but is definitely problematic in terms of variable scope): you define the page_number variable inside the scope of the if statement but then use it outside of that scope. That type of variable declaration should be avoided. You should declare the variable outside of the if statement.

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
  • ok.. but I need code to change pages right? any suggestion for the correct code would help me a lot thx – marcvienna Feb 01 '23 at 00:35
  • @marcvienna - well, I can only answer the original question you posted, which I've done. If you have a question about how to implement paging with serverside processing, I'd recommend you post a new question for that problem. – devlin carnate Feb 01 '23 at 00:38
  • @marcvienna : and by the way, I think you could solve your question about how to change pages by considering the fact that the `page.info` is indexed at zero. So if `page.info` equals `page.infos`, you want to set the page to 0. otherwise, do the math to determine what page you should be on and keep in mind that the property is indexed at zero. However, that;s just a guess because the scenario you set forth in this question is that you only have one page of data and only expect one page returned. – devlin carnate Feb 01 '23 at 00:42
  • 1
    if (info.start < info.end) { var page_number = (info.page + 1 < info.pages) ? info.page + 1 : 0; console.log(info.page); console.log(info.pages); } // issue solved!! – marcvienna Feb 01 '23 at 00:44