数据表+ PHP:多个表上的服务器端处理

时间:2016-08-27 16:29:35

标签: php mysql datatables server-side

如何获取Datatables 服务器端处理脚本以使用自定义查询?我需要从多个表中选择列并让Datatables渲染它们。

Datatables.net的PHP服务器端处理(SSP)总结如下:https://datatables.net/examples/server_side/simple.html

我发现了SO question,但原始海报从未提供过他的解决方案。我没有足够的声誉要求他提供更多细节。

这是我的原始SQL,没有使用Datatable的SSP

SELECT tbl_houses.style, tbl_houses.roomCount, tbl_residents.firstName, tbl_residents.lastName
FROM tbl_houses, tbl_residents
WHERE tbl_houses.houseID = tbl_residents.residentID

/* 
* # Equivalent query using JOIN suggested by @KumarRakesh
* # Note: JOIN ... ON is a synonym for INNER JOIN ... ON
* # Using JOIN conforms to syntax spec'd by ANSI-92 https://stackoverflow.com/a/894855/946957
*
* SELECT tbl_houses.style, tbl_houses.roomCount, tbl_residents.firstName, tbl_residents.lastName 
* FROM tbl_houses 
* JOIN tbl_residents ON tbl_houses.houseID = tbl_residents.residentID
*/

如何使用SSP让Datatables从上面运行查询?

看来server_processing.php只接受1个表格而没有自定义过滤(即WHERE条款。)

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

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

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

require( 'ssp.class.php' );

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

但是,ssp.class.php 支持使用WHERE进行过滤。我想我需要修改ssp.class.php以强制使用WHERE子句

更新

找到解决方案。我有空闲时间会发布。

6 个答案:

答案 0 :(得分:6)

ssp.class.php不支持联接和子查询,但有一种解决方法。诀窍是使用$table定义中的子查询,如下所示。将table替换为子查询中的实际表名。

$table = <<<EOT
 (
    SELECT 
      a.id, 
      a.name, 
      a.father_id, 
      b.name AS father_name
    FROM table a
    LEFT JOIN table b ON a.father_id = b.id
 ) temp
EOT;

$primaryKey = 'id';

$columns = array(
   array( 'db' => 'id',          'dt' => 0 ),
   array( 'db' => 'name',        'dt' => 1 ),
   array( 'db' => 'father_id',   'dt' => 2 ),
   array( 'db' => 'father_name', 'dt' => 3 )
);

$sql_details = array(
   'user' => '',
   'pass' => '',
   'db'   => '',
   'host' => ''
);

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

您还需要修改ssp.class.php并将FROM `$table`的所有实例替换为FROM $table以删除反引号。

确保所有列名称都是唯一的,否则请使用AS指定别名。

注意

还有github.com/emran/ssp存储库,其中包含支持JOIN的增强型ssp.class.php

LINKS

有关详细信息,请参阅jQuery DataTables: Using WHERE, JOIN and GROUP BY with ssp.class.php

答案 1 :(得分:3)

TL; DR:我最终使用了由Emran Ul Hadi实施的名为ssp.php的原始数据集ssp.class.php的修改:https://github.com/emran/ssp

他的修改接受JOIN,WHERE,GROUP BY和列别名。虽然该文件在一年多内没有更新,但它仍适用于DataTables 1.12.x.我对他的版本进行了一些修改,增加了它的稳健性,并通过更清晰的示例改进了文档。

当我有更多时间时,我会在这里发布我的mod /更新。最后,我希望提出一个pull-request来将我的更新发送到他的存储库中。

答案 2 :(得分:2)

看起来DataTables的脚本确实不是针对您的特定用例而设计的。但有一种方法允许自定义where子句和阅读ssp.class.php#complex的来源我认为此配置应该适用于您使用WHERE方法。 JOIN方法在这里不起作用。

长话短说:将server_processing.php编辑为:

<?php
// DB table to use
$table = 'tbl_houses, tbl_residents';

// First table's primary key
$primaryKey = 'tbl_houses.id';

$columns = [
    [ 'db' => 'tbl_houses.style'],
    [ 'db' => 'bl_houses.roomCount'],
    [ 'db' => 'tbl_residents.firstName'],
    [ 'db' => 'tbl_residents.lastName']

);

// connection details
$sql_details = [

];

$whereAll = 'tbl_houses.houseID = tbl_residents.residentID';

require( 'ssp.class.php' );

echo json_encode(
    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns , null, $whereAll);
);

complex方法接受您的自定义WHERE子句。但棘手的是使用2个表。这就是脚本似乎没有设计的目的。我看了一下它是如何构建最终的sql查询的,看起来你可能只在配置中使用这个table_name.field_name表示法,以及table_name, table_name表示$table表示法$primaryKey变量。

如上所述,DataTables脚本并不打算使用2个表。我不知道DataTables的所有功能是否都适用。

答案 3 :(得分:0)

我对原始Datatables ssp.class.php的贡献:https://github.com/emayskiy/Datatables-SSP-MultiTables

您可以为表和列添加别名,在其中使用表,并在表中使用[LEFT,INNER,RIGHT,CROSS] JOIN。 示例server_processing.php:

<?php 
    //For one table:
    //$table = "main_table_name";
    //Or for multitable queries: 
    $table = array(
        array('table'=>'main_table_name',  'as'=>'mt'),    
        array('table'=>'join1_table_name', 'as'=>'jt1', 'join_type'=>'INNER', 'join_on'=>'mt.field  = jt1.field'),
        array('table'=>'join2_table_name', 'as'=>'jt2', 'join_type'=>'LEFT',  'join_on'=>'mt.field1 = jt2.field')
    ); 
    //Columns definition with alias
    $columns = array(
        array( 'db' => 'mt.field1',  'dt' => 0 ),
        array( 'db' => 'mt.field2',  'dt' => 1 ),    
        array( 'db' => 'mt.name',    'as'=>'field3', 'dt' => 2 ),    
        array( 'db' => 'jt1.field1', 'as'=>'field4', 'dt' => 3 ),
        array( 'db' => 'jt2.field5', 'as'=>'field5', 'dt' => 4 )       
    );
    $primaryKey = 'mt.id'; //Primary key, for check records count
    $sql_details = array(
        'user' => $db_user,
        'pass' => $db_password,
        'db'   => $db_name,
        'host' => $db_host
    );
    $where = "mt.field1 > 10"; //You SQL where condition

    require('ssp.class.php' ); //File from github.com/emayskiy/Datatables-SSP-MultiTables
    echo json_encode(
        // All params same as in original class SSP
        SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns , '', $where)
    );

?>

答案 4 :(得分:0)

很抱歉,迟到了,但是我能够通过构建自己的服务器端文件来解决此问题,这样我就可以自定义查询和json输出。

文件服务器端自定义:

 public function produtosEstoque($arr)
    {
              
        //COLUNAS
        $column = array('prodNome', 'prodPreco', 'prodQtdEst', 'categDescricao');


        //SQL
        $query2 = "SELECT a.prodID, a.prodNome, a.prodMedida, a.prodPrecoAnt, a.prodPreco, a.prodCategoriaID, a.prodOferta,a.prodQtdEst, a.prodQtdMEst, b.categDescricao FROM produtos a INNER JOIN categoria b ON a.prodCategoriaID = b.categID WHERE a.prodEstatusID = 6 ";

        //SEARCH
        if ($arr['search']['value']) {
            $query2 .= "AND prodNome LIKE '%".$arr['search']['value']."%' ";
        }

        //ORDER
        if (isset($arr['order'])) {
            $query2 .= 'ORDER BY ' . $column[$arr['order']['0']['column']] . ' ' . $arr['order']['0']['dir'] . ' ';
        } else {
            $query2 .= 'ORDER BY a.prodID DESC ';
        }

        
        //LIMIT
        if ($arr["length"] != -1) {
            $query3 = 'LIMIT ' . $arr['start'] . ', ' . $arr['length'];
        }
        
        
        try {
            
            //TOTAL DE REGISTROS NA TABELA
            $query1 = "SELECT * FROM produtos WHERE prodEstatusID = 6";
            $stm1 = $this->pdo->prepare($query1);
            $stm1->execute();
            $contReg = $stm1->rowCount($stm1);   
            
            
            $stm = $this->pdo->prepare($query2);
            $stm->execute();
            $number_filter_row = $stm->rowCount($stm);


            $stm = $this->pdo->prepare($query2 . $query3);
            $stm->execute();
            $list = $stm->fetchAll(PDO::FETCH_OBJ);


            $data = [];
            foreach ($list as $row) {                                  
                $data[] = array('prod_nome' => $row->prodNome . ", " . $row->prodMedida, 'prod_preco' => "R$ ".$this->convInReal($row->prodPreco)." ".$this->formatProdOff($row->prodOferta), 'prod_estoque' => $row->prodQtdEst . " - M: " . $row->prodQtdMEst, 'prod_categoria' => $row->categDescricao);                                
            }

            $dat = array('draw' => intval($arr["draw"]), 
                  'recordsTotal' => $contReg, 
                  'recordsFiltered' => $number_filter_row, 
                  'data' => $data
                  );
            
            return json_encode($dat, JSON_UNESCAPED_UNICODE);

        } catch (PDOException $erro) {
            $data = array('msgEr' => 'ERR_002_EI', 'erroLine' => $erro->getLine());
            return json_encode($data);
        }
    }

答案 5 :(得分:0)

我通过在mysql phpmyadmin中创建视图表解决了这个问题。

在 phpmyadmin 中运行您的 sql 脚本,然后点击创建视图

enter image description here