Server side filtering

Server side filtering

edarrienedarrien Posts: 2Questions: 1Answers: 0

Hello,
am using Advanced Datable with server side processing. I would like to filter the results based on a ($_request) value. so not all opportunities show. Just the ones that match the value passed by the Ajax request. But all the data shows.

Here is the PHP side:

<?php

require_once dirname(__FILE__) . ("/../db_connection.php");
require_once dirname(__FILE__) . ("/../functions/common-functions.php");

    global $connection;
    $account_id = $_REQUEST['acct_id'];

  $aColumns = array( 'opportunity_id', 'opportunity_name','opportunity_stage_id', 'opportunity_close_date', 'opportunity_acccount_id', 
     'opportunity_amount', 'opportunity_type', 'opportunity_owner_id', 'opportunity_contact_id', 'opportunity_details');



  $sIndexColumn = "opportunity_acccount_id";
  $sTable = "opportunities_base";
  $sWhere = "opportunity_acccount_id = $account_id";  

  function fatal_error ( $sErrorMessage = '' )
  {
    header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
    die( $sErrorMessage );
  }


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

  $sOrder = "";
  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
   */
  $sWhere = "";
  if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
  {
    $sWhere = "WHERE (";
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      $sWhere .= "`".$aColumns[$i]."` LIKE '%".mysqli_real_escape_string($connection,  $_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 '%".mysqli_real_escape_string($connection, $_GET['sSearch_'.$i])."%' ";
    }
  }
  
  
  /*
   * SQL queries
   * Get data to display
   */
  $sQuery = "
    SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."`
    FROM   $sTable
    $sWhere
    $sOrder
    $sLimit
    ";
  $rResult = mysqli_query( $connection, $sQuery ) 
      or die("Error: ".mysqli_error($connection));
  
  /* Data set length after filtering */
  $sQuery = "
    SELECT FOUND_ROWS()
  ";
  $rResultFilterTotal = mysqli_query( $connection, $sQuery ) or die("Error: ".mysqli_error($connection));
  $aResultFilterTotal = mysqli_fetch_array($rResultFilterTotal);
  $iFilteredTotal = $aResultFilterTotal[0];
  
  /* Total data set length */
  $sQuery = "
    SELECT COUNT(`".$sIndexColumn."`)
    FROM   $sTable
    $sWhere
  ";
  $rResultTotal = mysqli_query($connection, $sQuery ) or die("Error: ".mysqli_error($connection));
  $aResultTotal = mysqli_fetch_array($rResultTotal);
  $iTotal = $aResultTotal[0];
  
  
  /*
   * Output
   */
  $output = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "aaData" => array()
  );
  
  while ( $aRow = mysqli_fetch_array( $rResult ) )
  {
    $row = array();   
     //$row[] =  $OpenAccountTasks;
    $row[] = '<img src="../assets/advanced-datatable/examples/examples_support/details_open.png">';
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      if ( $aColumns[$i] == "opportunity_name" )
      {
        /* Special output formatting for 'version' column */
       //$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
        $row[] = '<a href="AccountProfile.php?acctname=' .$aRow[ $aColumns[$i] ].'">' . $aRow[$aColumns[$i]] . '</a>';
      }
      if ( $aColumns[$i] == "opportunity_stage_id" )
      {
        $opportunity_stage_name = get_opportunity_stages($aRow['opportunity_stage_id']);
          $row[] = $opportunity_stage_name;
      }
      if ( $aColumns[$i] == "opportunity_owner_id" )
      {
        $opportunity_owner = get_user_info($aRow['opportunity_owner_id']);
        while ($owner_id = mysqli_fetch_array($opportunity_owner)) {
           $row[] = $owner_id['user_full_name'];
        }
      }
      if ( $aColumns[$i] == "opportunity_contact_id" )
      {
        $opportunity_contact = get_contact_info($aRow['opportunity_contact_id']);
        while ($contact= mysqli_fetch_array($opportunity_contact)) {
           $row[] = $contact['contact_fname'].' '. $contact['contact_lname'];
        }
         
      }
      else if ( $aColumns[$i] != ' ' )
      {
        /* General output */
        $row[] = $aRow[ $aColumns[$i] ];
      }
    }
    $output['aaData'][] = $row;
  }
  
  echo json_encode( $output );

<?php
>
```
And here is my Script: Which I also need to pass  value in , but for not its hard coded:
```
var oTable = $('#opportunities_table').dataTable( {
              // "aoColumnDefs": [
              //     { "bSortable": false, "aTargets": [ 0 ] }
              // ],
            "aaSorting": [[0, 'asc']],
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "../includes/functions/opportunity_json.php",
            "fnServerParams": function ( aoData ) {
                            aoData.push( { "name": "acct_id", "value": "3" } );
                          },
                    "aoColumns": [
            { "mData": "0" },
            { "mData": "2" },
            //Begin actual rows
            { "mData": "6" },
            { "mData": "10" },
            { "mData": "12" },
            { "mData": "8" },
            { "mData": "4" },
?>


          ],
          "sDom": '<"dt-panelmenu clearfix"Tfr>t<"dt-panelfooter clearfix"ip>',
                "oTableTools": {
                    "sSwfPath": "scripts/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
                }
 
          });

Any help is appreciated. Thank you.

This discussion has been closed.