datatables服务器端代码不起作用

时间:2014-06-23 10:38:59

标签: php datatable datatables jquery-datatables

我有一个56000条记录的数据库,我需要实现数据表服务器端代码。问题是我已经完成了完成这项任务的所有必要步骤,但仍然徒劳无功,给我提供了全套数据。

主要问题是当我的页面加载时,它会在运行时加载所有56000条记录,并导致页面在非结束状态下停止。

因此,一旦数据表正确实现,这个问题就会自动发生。 我希望在运行时完成此操作。 页面加载后,它应显示分页并拆分页面中的所有56000条记录。限制应该是50。

搜索和排序也无效。

这是我的JS功能:

<link href="//cdn.datatables.net/1.10.0/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="http://legacy.datatables.net/release-datatables/media/js/jquery.js"></script>
<script src="//legacy.datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
    $('#rounded-corner').dataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "<?php echo WEB_URL; ?>assets/common/authorsServerSide.php",
    } );
} );
</script>

这是我的HTML代码:

<table id="rounded-corner" summary="2007 Major IT Companies' Profit" class="display" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th scope="col" class="rounded-company">Sr No.</th>
        <th scope="col" class="rounded">Author Name</th>
        <th scope="col" class="rounded">Birth Year</th>
        <th scope="col" class="rounded">Death Year</th>
        <th scope="col" colspan="2" class="rounded-q4">Action</th>
      </tr>
    </thead>
    <tbody>
      <?php $count = 1; while($AuthorRecs = $RecordSet->fetch_object()){?>
      <tr>
        <td><?php echo $count++; ?></td>
        <td><?php print stripslashes(html_entity_decode($AuthorRecs->a_name)); ?></td>
        <td><?php print $AuthorRecs->a_birth; ?></td>
        <td><?php print $AuthorRecs->a_death; ?></td>
        <td><a href="editAuthors?a_ID=<?php echo $AuthorRecs->a_ID; ?>"><img src="../assets/styles/admin/images/user_edit.png" alt="" title="" border="0" /></a></td>
        <td><a href="process/adminProcess.php?page=deleteAuthors&a_ID=<?php echo $AuthorRecs->a_ID; ?>" class="ask"><img src="../assets/styles/admin/images/trash.png" alt="" title="" border="0" /></a></td>
      </tr>
      <?php } ?>
    </tbody>
  </table>

这是我的服务器端代码:

<?php
    /*
     * Script:    DataTables server-side script for PHP and MySQL
     * Copyright: 2010 - Allan Jardine, 2012 - Chris Wright
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array( 'a_ID', 'a_name', 'a_birth', 'a_death' );

    /* Indexed column (used for fast and accurate table cardinality) */
    //$sIndexColumn = "a_ID";

    /* DB table to use */
    $sTable = "authors";

    /* Database connection information */
    $gaSql['user']       = "root";
    $gaSql['password']   = "";
    $gaSql['db']         = "giftcardbooks";
    $gaSql['server']     = "localhost";


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */

    /*
     * Local functions
     */
    function fatal_error ( $sErrorMessage = '' )
    {
        header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
        die( $sErrorMessage );
    }


    /*
     * MySQL connection
     */
    if ( ! $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) )
    {
        fatal_error( 'Could not open connection to server' );
    }

    if ( ! mysql_select_db( $gaSql['db'], $gaSql['link'] ) )
    {
        fatal_error( 'Could not select database ' );
    }


    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
        $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".
            intval( $_GET['iDisplayLength'] );
    }


    /*
     * Ordering
     */
    $sOrder = "";
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }


    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" )
            {
                $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
        }
    }


    /*
     * SQL queries
     * Get data to display
     */
    $sQuery = "
        SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );

    /* Data set length after filtering */
    $sQuery = "
        SELECT FOUND_ROWS()
    ";
    $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
    $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];

    /* Total data set length */
    $sQuery = "
        SELECT COUNT(".$sIndexColumn.")
        FROM   $sTable
    ";
    $rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
    $aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];


    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = mysql_fetch_array( $rResult ) )
    {
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == "version" )
            {
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );
?>

2 个答案:

答案 0 :(得分:0)

看起来数据表函数的最后一行有一个额外的逗号。 “”

答案 1 :(得分:0)

您缺少应用搜索的脚本:

table.columns().every(function () {
    var that = this;

    $('input', this.footer()).on('keyup change', function () {
        if (that.search() !== this.value) {
            that.search(this.value).draw();
        }
    });
});