数据表搜索选项

时间:2012-07-16 11:05:40

标签: php search datatables jquery-datatables

我正在使用datatables插件,我正在搜索一个名为“privilege”的字段。 prvilege的值是“superadmin”和“admin”。对于外卡搜索,每当我通过“admin”搜索时,都会显示admin和superadmin的记录。如何解决这个问题。我的代码就像:

function fnFilterColumn ( i )
{
    $('#example').dataTable().fnFilter( 
     $("#col"+(i+1)+"_filter").val(),i,true,false);
}
$(document).ready(function(){
 var oTable = $('#example').dataTable( {
    "bProcessing": true,
    "sAjaxSource": "datatabledb.php",
    "bJQueryUI": true,
    "sPaginationType": "full_numbers",
    "sDom": 'T<"clear">lfrtip',
    "oTableTools": {
    "aButtons": [
    {
    "sExtends": "csv",
    "sButtonText": "Save to CSV"
    }
    ]
    },
    "oLanguage": {
        "sSearch": "Search all columns:"
    },
   "aoColumns": [
        null,
                 { "bSortable": false }, // disable the sorting property for checkbox header
        null,null,null,null,null,null,null,null
           ]
} );

在datatabledb.php文件中,我写下了我的数据库代码,如:

<?php
include('library/function.php');

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * 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( 'admin_name','admin_photo','username','email','age','location','contact_no','role','creation_date','status' );

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

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

    /* Database connection information */
    $gaSql['user']       = "root";
    $gaSql['password']   = "";
    $gaSql['db']         = "alert";
    $gaSql['server']     = "localhost";

    /* REMOVE THIS LINE (it just includes my SQL connection user/pass) */
    //include( $_SERVER['DOCUMENT_ROOT']."/datatables/mysql.php" );


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

    /* 
     * MySQL connection
     */
    $gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
        die( 'Could not open connection to server' );

    mysql_select_db( $gaSql['db'], $gaSql['link'] ) or 
        die( 'Could not select database '. $gaSql['db'] );


    /* 
     * Paging
     */
    $sLimit = "";

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


    /*
     * Ordering
     */
    $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] ) ]."` ".
                    mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }


    /* 
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            $sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string( $_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 '%".mysql_real_escape_string($_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 = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    /* Data set length after filtering */
    $sQuery = "
        SELECT FOUND_ROWS()
    ";
    $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];

    /* Total data set length */
    $sQuery = "
        SELECT COUNT(`".$sIndexColumn."`)
        FROM   $sTable
    ";
    $rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    $aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];


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

    while ( $aRow = mysql_fetch_array( $rResult ) )
    {
        $row = array();
        if($aRow['admin_name'] != ''){
            $row[] = wordwrap($aRow['admin_name'],15,"<br />\n",TRUE);

        }
        if($aRow['admin_photo'] == ''){
                $row[] = "<img src='http://fgtpl.com/fugenx1/public_html/alertR/admins/upload/no-pic.jpg' width='50' height='50'>";
        }
        else if($aRow['admin_photo'] != ''){
            $row[] ="<img src='http://fgtpl.com/fugenx1/public_html/alertR/admins/upload/".$aRow['admin_photo']."' width='50' height='50'>" ;
        }
        if($aRow['username'] != ''){
            $row[] = $aRow['username'];
        }
        if($aRow['email'] != ''){
            $row[] = wordwrap($aRow['email'],15,"<br />\n",TRUE);
        }
        else if($aRow['email'] == ''){
            $row[] = "N/A";
        }
        if($aRow['age'] != 0){
            $row[] = $aRow['age'];
        }
        else if($aRow['age'] == 0){
            $row[] = "N/A";
        }
        if($aRow['location'] != ''){
            $row[] = wordwrap($aRow['location'],20,"<br />\n",TRUE);
        }
        else if($aRow['location'] == ''){
            $row[] = "N/A";
        }
        if($aRow['contact_no'] != ''){
            $row[] = $aRow['contact_no'];
        }
        else if($aRow['contact_no'] == ''){
            $row[] = "N/A";
        } 
        if($aRow['role'] != ''){
            $row[] = get_role_name_by_id($aRow['role']);
        }
        if($aRow['creation_date'] != ''){
            $joiningDate = date("d-m-Y h:i:s", strtotime($aRow['creation_date']));
            $row[] = substr($joiningDate,0,10);
        }
        if($aRow['status'] != ''){
            $row[] = ($aRow['status'] == 1)?"Enable":"Disable";
        }





        $output['aaData'][] = $row;
    }


    echo json_encode( $output );
?> 

1 个答案:

答案 0 :(得分:1)

我不知道为什么这么长时间没有答案。你只需要改变

$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";

$sWhere .= "`".$aColumns[$i]."` LIKE '".mysql_real_escape_string( $_GET['sSearch'] )."' OR ";

删除通配符
您也可以为单个列执行此操作,如果您需要有关该

的详细信息,请告知我们