php – 如何在服务器端处理模式下使用JOIN进行数据库查询

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 如何在服务器端处理模式下使用JOIN进行数据库查询脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_512_1@
我在我的视图列表中使用jquery DataTables.我使用服务器端处理模式,特别适用于大型数据集.但我的问题是我只能使用单个数据库表来执行此操作.

如何使用自定义查询使用多个表和JOIN而不会改变太多是我的代码

所以我有这个:

HTML

<table id="CustomerList" class="table table-striPEd table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th colspan="7"> <center>Customer Information<center></th>
            <th colspan="1"> <center>Actions<center></th>
        </tr>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Gender</th>
            <th>Phone Number</th>
            <th>Country</th>
            <th>Postcode</th>
            <th>EdIT</th>
        <!--     <th>Edit</th>
            <th>Delete</th> -->
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

阿贾克斯

<script type="text/javascript">
$(document).ready(function() {
    $.fn.dataTable.ext.legacy.ajax = true;
    VAR table = $('#CustomerList').DataTable( {
       "PRocessing": true,"serverSide": true,"ajax": "api/customer/all","columnDefs": [
            { 
                "targets": 7,"render": function(data,type,row,Meta){
                   // return '<a href="/qms/public/customer/' + row[0] + '/edit">Edit</a>';  
                   return "<a class='BTn btn-small btn-info' href='<?PHP echo URL::to('customer').'/';?>"+row[0]+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>";  
                }
            }            
        ]        
    });
    var tt = new $.fn.dataTable.TableTools( $('#CustomerList').DataTable() );
    $( tt.fnContainer() ).insertBefore('div.dataTables_wrapper');
});

调节

public function apiGetCustomers()
{
    /*=================================================================*/
    /*
     * Script:    DataTables server-side script for PHP and Postgresql
     * Copyright: 2010 - Allan Jardine
     * 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('id','firstname','lastname','gender','phone_num','country','postcode' );

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

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

    /* Database connection information */
    $gasql['user']       = "postgres";
    $gasql['password']   = "postgres";
    $gasql['db']         = "qms";
    $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
     */

    /*
     * DB connection
     */
    $gasql['link'] = pg_connect(
        " host=".$gasql['server'].
        " dbname=".$gasql['db'].
        " user=".$gasql['user'].
        " password=".$gasql['password']
    ) or die('Could not connect: ' . pg_last_error());


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


    /*
     * Ordering
     */
    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 assumes that the field that is being seArched on is a string typed field (ie. one
     * on which ILIKE can be used). Boolean fields etc will need a modification here.
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $_GET['bSearchable_'.$i] == "true" )
            {
                if($aColumns[$i] != 'id') // Exclude ID for filtering
                {
                    $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
                }
            }
        }
        $sWhere = substr_replace( $sWhere,-3 );
        $sWhere .= ")";
    }

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


    $sQuery = "
        SELECT ".str_replace(","," ",implode(",$aColumns))."
        From   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";

    $rResult = pg_query( $gasql['link'],$sQuery ) or die(pg_last_error());

    $sQuery = "
        SELECT $sIndexColumn
        From   $sTable
    ";
    $rResulttotal = pg_query( $gasql['link'],$sQuery ) or die(pg_last_error());
    $iTotal = pg_num_rows($rResultTotal);
    pg_free_result( $rResultTotal );

    if ( $sWhere != "" )
    {
        $sQuery = "
            SELECT $sIndexColumn
            FROM   $sTable
            $sWhere
        ";
        $rResultFilterTotal = pg_query( $gasql['link'],$sQuery ) or die(pg_last_error());
        $iFilteredTotal = pg_num_rows($rResultFilterTotal);
        pg_free_result( $rResultFilterTotal );
    }
    else
    {
        $iFilteredTotal = $iTotal;
    }

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

    while ( $aRow = pg_fetch_array($rResult,null,PGsql_ASSOC) )
    {
        $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 );

    // Free resultset
    pg_free_result( $rResult );

    // Closing connection
    pg_close( $gasql['link'] );


}

在我的控制器中,您可以看到$aColumns,其中包含我希望在表客户中获得的表列

如果我想要一个自定义查询获取数据,如下所示:

$query = "SELECT a.id as crmid,b.name,a.title,a.firstname,a.surname,a.disposition,a.gross,a.created_at,a.phone_num FROM forms a INNER JOIN users b ON a.agent_id = b.id;";

所以我有内部联接而不是只有一个表.

解决方法

一个技巧可以使用JOIN而不会过多地修改代码.

改变这一行:

$sTable = "customers";

至:

$sTable = 
   "( 
      SELECT a.id AS crmid,b.name 
      FROM forms a 
      INNER JOIN users b ON a.agent_id = b.id 
    ) table";

我为了代码清晰起见简化了上面的查询.只需确保所有列名都是唯一的,否则请在需要时使用别名.

然后在$aColumns变量中使用列名/别名.对于上面的查询,它将是

$aColumns = array('crmid','name');

脚本宝典总结

以上是脚本宝典为你收集整理的php – 如何在服务器端处理模式下使用JOIN进行数据库查询全部内容,希望文章能够帮你解决php – 如何在服务器端处理模式下使用JOIN进行数据库查询所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。