简体   繁体   中英

(Codeigniter) jQuery datatable server-side processing with sql server

i have an issue with jQuery datatables i want to use server-side processing, because to much data to load. but from the documentation i have read it use native php, i use codeigniter 3. it quite difficult to modify the code. here's the code i use in my controller

public function dataTable()
{
    $sIndexColumn = "";
    $sTable = "myTable";

    $gaSql['user']       = "test";
    $gaSql['password']   = "t3st";
    $gaSql['db']         = "myDatabase";
    $gaSql['server']     = "Driver={SQL Server Native Client 10.0};Server=ITI-0299-PC\JTSMSSQLSERVER;Port=1326;Database=myDatabase; Uid=test;Pwd=t3st;"; //Locale

    $aColumns = array(
        'id','nmrumahsakit','alamat','kota',
        'provinsi','rawat_inap','rawat_jalan',
        'mcu','telp','fax','latitude',
        'longitude','created_at','updated_at');

    /*
     * ODBC connection
     */
    $connectionInfo = array("UID" => $gaSql['user'], "PWD" => $gaSql['password'], "Database"=>$gaSql['db'],"ReturnDatesAsStrings"=>true);
    $gaSql['link'] = sqlsrv_connect( $gaSql['server'], $connectionInfo);
    $params = array();
    $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );


    /* Ordering */
    $sOrder = "";
    if ( isset( $_GET['iSortCol_0'] ) ) {
            $sOrder = "ORDER BY id  ";
            for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
                    if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
                            $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                                    ".addslashes( $_GET['sSortDir_'.$i] ) .", ";
                    }
            }
            $sOrder = substr_replace( $sOrder, "", -2 );
            if ( $sOrder == "ORDER BY id" ) {
                    $sOrder = "";
            }
    }

    /* Filtering */
    $sWhere = "";
    if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
            $sWhere = "WHERE (";
            for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                    $sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_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 '%".addslashes($_GET['sSearch_'.$i])."%' ";
            }
    }

    /* Paging */
    $top = (isset($_GET['iDisplayStart']))?((int)$_GET['iDisplayStart']):0 ;
    $limit = (isset($_GET['iDisplayLength']))?((int)$_GET['iDisplayLength'] ):10;
    $sQuery = "SELECT TOP $limit ".implode(",",$aColumns)."
            FROM $sTable
            $sWhere ".(($sWhere=="")?" WHERE ":" AND ")." $sIndexColumn NOT IN
            (
                    SELECT $sIndexColumn FROM
                    (
                            SELECT TOP $top ".implode(",",$aColumns)."
                            FROM $sTable
                            $sWhere
                            $sOrder
                    )
                    as [virtTable]
            )
            $sOrder";

    $rResult = sqlsrv_query($gaSql['link'],$sQuery) or die("$sQuery: " . sqlsrv_errors());

    $sQueryCnt = "SELECT * FROM $sTable $sWhere";
    $rResultCnt = sqlsrv_query( $gaSql['link'], $sQueryCnt ,$params, $options) or die (" $sQueryCnt: " . sqlsrv_errors());
    $iFilteredTotal = sqlsrv_num_rows( $rResultCnt );

    $sQuery = " SELECT * FROM $sTable ";
    $rResultTotal = sqlsrv_query( $gaSql['link'], $sQuery ,$params, $options) or die(sqlsrv_errors());
    $iTotal = sqlsrv_num_rows( $rResultTotal );

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

    while ( $aRow = sqlsrv_fetch_array( $rResult ) ) {
            $row = array();
            for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                    if ( $aColumns[$i] != ' ' ) {
                            $v = $aRow[ $aColumns[$i] ];
                            $v = mb_check_encoding($v, 'UTF-8') ? $v : utf8_encode($v);
                            $row[]=$v;
                    }
            }
            If (!empty($row)) { $output['aaData'][] = $row; }
    }
    echo json_encode( $output );
}

in this is js configuration for datatables:

 $('#datatable2').dataTable({
    "sScrollY": "400px",
    "bProcessing": true,
          "bServerSide": true,
          "sServerMethod": "GET",
          "sAjaxSource": "<?php echo base_url(); ?>mycontroller/mymethod",
          "iDisplayLength": 10,
          "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
          "aaSorting": [[0, 'asc']],
          "aoColumns": [
      { "bVisible": true, "bSearchable": true, "bSortable": true },
      { "bVisible": true, "bSearchable": true, "bSortable": true },
      { "bVisible": true, "bSearchable": true, "bSortable": true }
      ]
  }).fnSetFilteringDelay(700);
    });

and this is the view:

<table id="datatable2" class="table table-bordered table-hover">
            <thead>
              <tr>
                <th>No</th>
                <th>Nama R.S</th>
                <th>Alamat</th>
                <th>Kota</th>
                <th>Provinsi</th>
                <th>Rawat Inap</th>
                <th>Rawat Jalan</th>
                <th>MCU</th>
                <th>No.Telp</th>
                <th>No.Fax</th>
                <th>Latitude</th>
                <th>Longitude</th>
                <th>Created At</th>
                <th>Updated At</th>
                <th>Menu</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>

after test it, ive got this error.

A PHP Error was encountered

Severity: Error

Message: Call to undefined function sqlsrv_connect()

Filename: controllers/Provider.php

Line Number: 302

Backtrace:

I already use connection in config/database.php and my question is how to user server-side processing in codeigniter?

Problem above solve, but i've got new problem with js.

DataTables warning (table id = 'datatable2'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.

CMIIW

It seems that your PHP installation is missing an extension that allows you to use the sqlsrv_connect function.

Make sure that php_sqlsrv_XX_ts.dll extension is loaded in your php.ini.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM