【问题标题】:DataTables Search, Orderby not working数据表搜索,Orderby 不工作
【发布时间】:2016-02-23 08:21:47
【问题描述】:

这是我的服务器端代码:

<?php

namespace App\Helpers;

use PDO;
use PDOException;

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);


class DataTables {

    private $_db;

    public function __construct() {

        try {
            $host       = 'localhost';
            $database   = 'zzzzzzzzz';
            $user       = 'xxxxxxxxxxx';
            $passwd     = 'yyyyyyyyyyyyyyyy';

            $this->_db = new PDO('mysql:host='.$host.';dbname='.$database, $user, $passwd, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
        } catch (PDOException $e) {
            error_log("Failed to connect to database: ".$e->getMessage());
        }

    }


    public function get($table, $index_column, $columns) {
        // Paging
        $sLimit = "LIMIT 1";
        if ( isset( $_GET['start'] ) && $_GET['length'] != '-1' ) {
            $sLimit = "LIMIT ".intval( $_GET['start'] ).", ".intval( $_GET['length'] );
        }

        // Ordering
        $sOrder = '';
        if ( isset($request['order']) && count($request['order']) ) {
            $orderBy = array();
            $dtColumns = self::pluck( $columns, 'dt' );
            for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
                // Convert the column index into the column data property
                $columnIdx = intval($request['order'][$i]['column']);
                $requestColumn = $request['columns'][$columnIdx];
                $columnIdx = array_search( $requestColumn['data'], $dtColumns );
                $column = $columns[ $columnIdx ];
                if ( $requestColumn['orderable'] == 'true' ) {
                    $dir = $request['order'][$i]['dir'] === 'asc' ?
                        'ASC' :
                        'DESC';
                    $orderBy[] = '`'.$column['db'].'` '.$dir;
                }
            }
            $sOrder = 'ORDER BY '.implode(', ', $orderBy);
        }

        /*
         * 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($columns) ; $i++ ) {
                if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" ) {
                    $sWhere .= "`".$columns[$i]."` LIKE :search OR ";
                }
            }
            $sWhere = substr_replace( $sWhere, "", -3 );
            $sWhere .= ')';
        }

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

        // SQL queries get data to display
        $sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $columns))."` FROM `".$table."` ".$sWhere." ".$sOrder." ".$sLimit;
        $statement = $this->_db->prepare($sQuery);

        // Bind parameters
        if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
            $statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
        }
        for ( $i=0 ; $i<count($columns) ; $i++ ) {
            if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
                $statement->bindValue(':search'.$i, '%'.$_GET['sSearch_'.$i].'%', PDO::PARAM_STR);
            }
        }
        $statement->execute();

        $iFilteredTotal = current($this->_db->query('SELECT FOUND_ROWS()')->fetch());

        // Get total number of rows in table
        $sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."`";
        $iTotal = current($this->_db->query($sQuery)->fetch());

        // Fetch Results
        $clans = array();
        $rownumber = $_GET['start']+1;

        while($clan = $statement->fetch()){
            $clan['rownumber'] =  intval($rownumber);
            $clans[] = $clan;
            $rownumber++;
        }


        // Output
        $output = array(
            "draw" => intval($_GET['draw']),
            "recordsTotal" => intval($iTotal),
            "recordsFiltered" => intval($iFilteredTotal),
            "data" => $clans
        );

        echo json_encode((object)$output );
    }


}

header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
?>

有一个实时 URL:http://clashdata.tk/clans/

分页工作正常,但如果我尝试对列进行排序或排序,那么它会给出第一次显示的正常查询。我想我可能有错误的服务器代码。我正在使用版本 DataTables 版本 1.10.10。

有谁知道需要改变什么才能让它工作?

非常感谢!

【问题讨论】:

    标签: javascript php jquery mysql datatables


    【解决方案1】:

    为什么您不尝试使用 javascript sorteable 而不是对数据库进行大量查询,这对用户来说既简单又快速。

    在表格标签处添加:

    class='sortable'
    

    并在表格末尾添加:

    <script type="text/javascript" src="script.js"></script>
       <script type="text/javascript">
     var sorter = new TINY.table.sorter("sorter");
       sorter.head = "head";
       sorter.asc = "asc";
       sorter.desc = "desc";
       sorter.even = "evenrow";
       sorter.odd = "oddrow";
       sorter.evensel = "evenselected";
    sorter.oddsel = "oddselected";
    sorter.paginate = true;
    sorter.currentid = "currentpage";
    sorter.limitid = "pagelimit";
    sorter.init("table",10);//here is the default sorter
     </script>   
    

    【讨论】:

    • 它破坏了数据的全部意义..,我使用它来运行查询,我不必获取需要 30+ sedonds 的整个表
    猜你喜欢
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多