【问题标题】:How to use 'WHERE' clause using ssp.class.php DataTables如何使用 ssp.class.php DataTables 使用“WHERE”子句
【发布时间】:2014-10-29 22:10:22
【问题描述】:

好的,我正在尝试使用 jQuery DataTable (DataTables.net) 从我的数据库中显示信息。 我可以让它正常显示整个表格的“笔记”,但我只想显示尚未阅读的笔记。所以我需要以某种方式包含一个 WHERE 子句,但我不清楚解决这个问题的最佳方法。

这是我目前显示整个表格的方式:

// DB table to use
$table = 'Notes';

// Table's primary key
$primaryKey = 'CID';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'CID', 'dt' => 0 ),

array(
    'db'        => 'CID',
    'dt'        => 0,
    'formatter' => function( $d, $row ) {
        return '<a href="profile.php?search='.$d.'" target="_Blank">'.$d."</a>";
    }
),

array( 'db' => 'Title', 'dt' => 1 ),
array( 'db' => 'Name',  'dt' => 2 ),
array(
    'db'        => 'Date',
    'dt'        => 3,
    'formatter' => function( $d, $row ) {
        return date( 'jS M y', strtotime($d));
        }
    )
);

// SQL server connection information
$sql_details = array(
'user' => '*DB_USER*',
'pass' => '*Password*',
'db'   => '*DatabaseName*',
'host' => 'localhost'
);
require( 'ssp.class.php' );

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

我需要相当于SELECT * FROM Notes WHERE Status ='Unread'

【问题讨论】:

标签: php jquery mysql sql jquery-datatables


【解决方案1】:

您应该更改 DataTables 的默认函数来执行此操作!

使用这个ssp.class.php自定义类

Link

像下面的例子一样使用它:

require( 'ssp.class.php' );
$where = "Status ='Unread'";
echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns,$where )
);

如果设置$where参数,自定义类会在select语句中添加where子句!

更新

2015年DataTables添加复杂方法

新的内置方法可以在查询中设置where子句!

【讨论】:

  • 你的代码有错误,应该是: SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns,$where )添加了对 where 子句的支持,使用 SSP:simple 将忽略您刚刚添加的查询。我已经编辑了你的答案。检查文档:github.com/DataTables/DataTablesSrc/blob/master/examples/…
  • 先看答案!我创建了一个自定义类并使用它(查看 github 链接),正如我提到的 2014 年没有复杂的方法,这就是我编写该类的原因!
  • 那我的错!抱歉,我认为这是一个错字,实际上相当混乱。如果您在更新段落下添加复杂的代码,这可能是一个好主意,可能会消除混乱。
【解决方案2】:

嗯.. 你不能不编辑或扩展SSP。这是一种非常糟糕的风格,有很多复制的代码,但是SSP 不允许更好的自定义......

class SSPCustom extends SSP
{
    /**
     *  @param  array $request Data sent to server by DataTables
     *  @param  array $sql_details SQL connection details - see sql_connect()
     *  @param  string $table SQL table to query
     *  @param  string $primaryKey Primary key of the table
     *  @param  array $columns Column information array
     *  @param  string $whereCustom Custom (additional) WHERE clause
     *  @return array          Server-side processing response array
     */
    static function simpleCustom ( $request, $sql_details, $table, $primaryKey, $columns, $whereCustom = '' )
    {
        $bindings = array();
        $db = self::sql_connect( $sql_details );

        // Build the SQL query string from the request
        $limit = self::limit( $request, $columns );
        $order = self::order( $request, $columns );
        $where = self::filter( $request, $columns, $bindings );

        if ($whereCustom) {
            if ($where) {
                $where .= ' AND ' . $whereCustom;
            } else {
                $where .= 'WHERE ' . $whereCustom;
            }
        }

        // Main query to actually get the data
        $data = self::sql_exec( $db, $bindings,
            "SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."`
             FROM `$table`
             $where
             $order
             $limit"
        );

        // Data set length after filtering
        $resFilterLength = self::sql_exec( $db,
            "SELECT FOUND_ROWS()"
        );
        $recordsFiltered = $resFilterLength[0][0];

        // Total data set length
        $resTotalLength = self::sql_exec( $db,
            "SELECT COUNT(`{$primaryKey}`)
             FROM   `$table`
             WHERE  " . $whereCustom
        );
        $recordsTotal = $resTotalLength[0][0];


        /*
         * Output
         */
        return array(
            "draw"            => intval( $request['draw'] ),
            "recordsTotal"    => intval( $recordsTotal ),
            "recordsFiltered" => intval( $recordsFiltered ),
            "data"            => self::data_output( $columns, $data )
        );
    }
}

调用它:

echo json_encode(
    SSPCustom::simpleCustom( $_GET, $sql_details, $table, $primaryKey, $columns, "Status ='Unread'" )
);

未经测试

【讨论】:

    【解决方案3】:

    你可以像这样使用 where 子句;

    $data = SSP::sql_exec( $db, $bindings,
       "SELECT SQL_CALC_FOUND_ROWS ".implode(", ", SSP::pluck($columns, 'db'))."
        FROM $table where Status = 'Unread' // <--where clause here
        $where
        $order
        $limit"
    );
    

    【讨论】:

    • 如何将其与echo json_encode( SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns ) ); 一起使用,因为我正在使用 json_encode 获取数据
    【解决方案4】:

    我也能够解决这个问题,但在 ssp.class.php 过滤器函数中插入了一些代码。下面是插入了示例自定义 where 子句的函数列表。该课程的“简单”功能将在没有任何进一步的陪审团操纵的情况下工作。优点是它可以很好地与数据表的文本搜索功能配合使用。

    static function filter ( $request, $columns, &$bindings )
    {
        $globalSearch = array();
        $columnSearch = array();
        $dtColumns = self::pluck( $columns, 'dt' );
    
        if ( isset($request['search']) && $request['search']['value'] != '' ) {
            $str = $request['search']['value'];
    
            for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
                $requestColumn = $request['columns'][$i];
                $columnIdx = array_search( $requestColumn['data'], $dtColumns );
                $column = $columns[ $columnIdx ];
    
                if ( $requestColumn['searchable'] == 'true' ) {
                    $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                    $globalSearch[] = "`".$column['db']."` LIKE ".$binding;
                }
            }
        }
    
        // Individual column filtering
        for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
            $requestColumn = $request['columns'][$i];
            $columnIdx = array_search( $requestColumn['data'], $dtColumns );
            $column = $columns[ $columnIdx ];
    
            $str = $requestColumn['search']['value'];
    
            if ( $requestColumn['searchable'] == 'true' &&
             $str != '' ) {
                $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                $columnSearch[] = "`".$column['db']."` LIKE ".$binding;
            }
        }
    
        // Combine the filters into a single string
        $where = '';
    
        if ( count( $globalSearch ) ) {
            $where = '('.implode(' OR ', $globalSearch).')';
        }
    
        if ( count( $columnSearch ) ) {
            $where = $where === '' ?
                implode(' AND ', $columnSearch) :
                $where .' AND '. implode(' AND ', $columnSearch);
        }
    
            //------------------------------------------------------------
            //############################################################
            //EXAMPLE ADDITIONAL WHERE CONDITIONS HERE. THIS IS EQUIVALENT
            //TO "WHERE id = 1"
            $where = ($where === '') ? 
                "id = ".self::bind( $bindings, 1, PDO::PARAM_INT) :
                $where ." AND "."id = ".self::bind( $bindings, 1, PDO::PARAM_INT);
            //############################################################
            //############################################################
            //------------------------------------------------------------
    
    
        if ( $where !== '' ) {
            $where = 'WHERE '.$where;
        }
    
        return $where;
    }
    

    【讨论】:

      【解决方案5】:

      万一其他人偶然发现了这一点,现在正确答案是:

      require( 'ssp.class.php' );
      $where = "Status ='Unread'";
      echo json_encode(
          SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, $where )
      );
      

      不需要 3rd 方类,此功能内置于 DataTables 中。

      【讨论】:

        猜你喜欢
        • 2017-02-19
        • 2012-03-15
        • 1970-01-01
        • 2011-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-25
        相关资源
        最近更新 更多