数据表过滤,搜索不起作用的mongodb php

时间:2017-06-19 10:13:49

标签: php mysql mongodb

在这个代码过滤器中,搜索和分页无法正常运行我已经尝试过但是它没有用,所以请检查代码给我任何解决方案或任何有关此查询的参考。即使任何与此代码文件或文档相关的内容,对我来说都有助于实现这一概念

    <?php

mb_internal_encoding('UTF-8');

$database   = 'test';
$collection = 'user';

/**
 * MongoDB connection
 */
try{
        // Connecting to server
        $m = new MongoClient(  );
    }catch(MongoConnectionException $connectionException){
        print $connectionException;
        exit;
    }

$m_collection = $m->$database->$collection;    
$input = $fields = $totalRecords = $data = array();
$input = & $_REQUEST;
$fields = array('id', 'name', 'email', 'gender,');

// Input method (use $_GET, $_POST or $_REQUEST)


/**
 * Handle requested DataProps
 */

// Number of columns being displayed (useful for getting individual column search info)
$iColumns = & $input['iColumns'];

// Get mDataProp values assigned for each table column
$dataProps = array();
for ($i = 0; $i < $iColumns; $i++) {
    $var = 'mDataProp_'.$i;
    if (!empty($input[$var]) && $input[$var] != 'null') {
        $dataProps[$i] = $input[$var];
    }
}

$searchTermsAny = array();
$searchTermsAll = array();

if ( !empty($input['sSearch']) ) {
    $sSearch = $input['sSearch'];

    for ( $i=0 ; $i < $iColumns ; $i++ ) {
        if ($input['bSearchable_'.$i] == 'true') {
            if ($input['bRegex'] == 'true') {
                $sRegex = str_replace('/', '\/', $sSearch);
            } else {
                $sRegex = preg_quote($sSearch, '/');
            }
            $searchTermsAny[] = array(
                $dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i' )
            );
        }
    }
}

// Individual column filtering
for ( $i=0 ; $i < $iColumns ; $i++ ) {
    if ( $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
        if ($input['bRegex_'.$i] == 'true') {
            $sRegex = str_replace('/', '\/', $input['sSearch_'.$i]);
        } else {
            $sRegex = preg_quote($input['sSearch_'.$i], '/');
        }
        $searchTermsAll[ $dataProps[$i] ] = new MongoRegex( '/'.$sRegex.'/i' );
    }
}

$searchTerms = $searchTermsAll;
if (!empty($searchTermsAny)) {
    $searchTerms['$or'] = $searchTermsAny;
}
 $totalRecords =$m_collection->count();
$cursor = $m_collection->find($searchTerms, $fields);

/**
 * Paging
 */
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
    $cursor->limit( $input['iDisplayLength'] )->skip( $input['iDisplayStart'] );
}

/**
 * Ordering
 */
if ( isset($input['iSortCol_0']) ) {
    $sort_fields = array();
    for ( $i=0 ; $i<intval( $input['iSortingCols'] ) ; $i++ ) {
        if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
            $field = $dataProps[ intval( $input['iSortCol_'.$i] ) ];
            $order = ( $input['sSortDir_'.$i]=='desc' ? -1 : 1 );
            $sort_fields[$field] = $order;
        }
    }
    $cursor->sort($sort_fields);
}


foreach ( $cursor as $doc ) 
{   $name = '<a href="profile.php?secure='.$doc['_id'].' " style = "color:red;">'.$doc['name'].'</a>';
    $data[] = array($name, $doc['email'], $doc['gender]);
}

/**
 * Output
 */
$json_data = array(  
     "draw"=> intval( $input['draw'] ),
   "recordsTotal" =>intval ($totalRecords),
    "recordsFiltered" => intval($totalRecords),
    "data"            => $data

);    

echo json_encode( $json_data );
And also i need to Join two tables as given below.

表1

Table 1

表2

Table

1 个答案:

答案 0 :(得分:3)

我这样做:

$('#datatable_emp_details').dataTable({
    "sServerMethod": "POST", 
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "get_data.php"
});

get_data.php:

<?php
$mongo      = new MongoClient();
$database   = $mongo->selectDb('dbtest');
$collection = $database->selectCollection('empDetails');
$skip       = (int)$_REQUEST['iDisplayStart'];
$limit      = (int)$_REQUEST['iDisplayLength'];
$search     = $_REQUEST['sSearch'];
$sortIndex  = $_REQUEST['iSortCol_0'];

$sortArray  = array('emp_id', 'first_name', 'last_name', 'position', 'email', 'office', 'start_date', 'age', 'salary', 'projects'
);
$sortByCol  = $sortArray[$sortIndex];
$sortTypeTxt= $_REQUEST['sSortDir_0'];  // asc/desc
$sortType = -1;
if( $sortTypeTxt == 'asc' )
{
    $sortType = 1;
}
if( $search != '' )
{
    $condtion = array(
                    '$or' => array(
                        array('emp_id'    => $search),
                        array('first_name'=> new MongoRegex('/'. $search .'/i')),   // i for case insensitive
                        array('last_name' => new MongoRegex('/'. $search .'/i')),
                        array('position'  => new MongoRegex('/'. $search .'/i')),
                        array('email'     => new MongoRegex('/'. $search .'/i')),
                        array('office'    => new MongoRegex('/'. $search .'/i')),
                        array('start_date'=> new MongoRegex('/'. $search .'/i')),
                        array('age'       => new MongoRegex('/'. $search .'/i')),
                        array('salary'    => new MongoRegex('/'. $search .'/i')),
                        array('projects'  => new MongoRegex('/'. $search .'/i'))
                    )
                );
    $resultSet =   $collection->find($condtion)->limit($limit)->skip($skip)->sort(array($sortByCol => $sortType));
}
else
{
    $resultSet  = $collection->find()->limit($limit)->skip($skip)->sort(array($sortByCol => $sortType))->sort(array($sortByCol => $sortType));
}
$data = array();
if( count( $resultSet ) > 0 )
{
    foreach ($resultSet as $document)
    {
        $data[] = $document;
    }
}
$resultSet  = $collection->find();
$iTotal     = count($resultSet);
$rec = array(
    'iTotalRecords' => $iTotal,
    'iTotalDisplayRecords' => $iTotal,
    'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data)) {
    foreach ($data as $item) {
        $rec['aaData'][$k] = array(
            0  => $item['emp_id'],
            1  => $item['first_name'],
            2  => $item['last_name'],
            3  => $item['position'],
            4  => $item['email'],
            5  => $item['office'],
            6  => $item['start_date'],
            7  => $item['age'],
            8  => $item['salary'],
            9  => $item['projects'],
            10 => '<a href="javascript:void(0);" class="edit_emp" id="'. $item['emp_id'] .'">Edit</a> | <a href="javascript:void(0);" class="delete_emp" id="'. $item['emp_id'] .'">Delete</a>'
        );
        $k++;
    }
}
echo json_encode($rec);
exit;
?>

Github repository link