【问题标题】:How to search word by word using this approach (datatables)?如何使用这种方法(数据表)逐字搜索?
【发布时间】:2016-01-20 01:39:08
【问题描述】:

这是我使用的代码,它只搜索(从第一个字母到最后一个字母)而不是逐字搜索。怎么可能逐字逐句(关键字)?

<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sample";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
mysqli_set_charset($conn,"utf8");
/* Database connection end */


// storing  request (ie, get/post) global array to a variable  
$requestData= $_REQUEST;


$columns = array( 
// datatable column index  => database column name
    0=> 'app_id',
    1 =>'fullname',


);

// getting total number records without any search
$sql = "SELECT app_id";
$sql.=" FROM applicants";
$query=mysqli_query($conn, $sql) or die("employee-grid-data1.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.


$sql = "SELECT app_id, fullname";
$sql.=" FROM applicants WHERE 1=1";
if( !empty($requestData['search']['value']) ) {   // if there is a search parameter, $requestData['search']['value'] contains search parameter
    $sql.=" AND ( app_id LIKE '".$requestData['search']['value']."%' ";    
    $sql.=" OR fullname LIKE '".$requestData['search']['value']."%' ";
    $sql.=" OR contact LIKE '".$requestData['search']['value']."%' ";
    $sql.=" OR address LIKE '".$requestData['search']['value']."%' ";
    $sql.=" OR photo LIKE '".$requestData['search']['value']."%' ";
    $sql.=" OR datereg LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data1.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. 
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc  */    
$query=mysqli_query($conn, $sql) or die("employee-grid-data1.php: get employees");
$data = array();
while( $row=mysqli_fetch_array($query) ) {  // preparing an array
    $nestedData=array(); 
    $nestedData[] = $row["app_id"];
    $nestedData[] = $row["fullname"];

    $data[] = $nestedData;
}



$json_data = array(
            "draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
            "recordsTotal"    => intval( $totalData ),  // total number of records
            "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
            "data"            => $data   // total data array
            );

echo json_encode($json_data);  // send data as json format

?>

问题:它是从第一个字母到最后一个字母的开始,而不是一个字一个字。可以逐字逐句吗?

source

【问题讨论】:

  • 我真的不明白你想要什么。你能举个例子说明“逐字”是什么意思吗?不是代码,你真正的意思应该是输出。
  • @davidkonrad 关键字。

标签: mysqli datatables


【解决方案1】:

这是由 Gyrocode.com 提供的解决方案

    // If there is a search parameter
if( !empty($requestData['search']['value']) ) {   
    $search = mysqli_real_escape_string(
       $conn,
       // Match beginning of word boundary
       "[[:<:]]".
       // Replace space characters with regular expression
       // to match one or more space characters in the target field
       implode("[[.space.]]+",             
          preg_split("/\s+/", 
             // Quote regular expression characters
             preg_quote(trim($requestData['search']['value']))
          )
       ).
       // Match end of word boundary
       "[[:>:]]"
    );


    $sql.=" AND ( app_id REGEXP '$search' ";    
    $sql.=" OR fullname REGEXP '$search' ";
    $sql.=" OR contact REGEXP '$search' ";
    $sql.=" OR address REGEXP '$search' ";
    $sql.=" OR photo REGEXP '$search' ";
    $sql.=" OR datereg REGEXP '$search' )";
}

【讨论】:

    【解决方案2】:

    您可以使用REGEXP 以及[[:&lt;:]][[:&gt;:]] 单词边界标记来仅匹配单词。

    例如:

    SELECT *
    FROM table 
    WHERE keywords REGEXP '[[:<:]]word[[:>:]]'
    

    您还需要使用mysqli_real_escape_string() 转义数据。

    查看下面的更新代码:

    // If there is a search parameter
    if( !empty($requestData['search']['value']) ) {   
        $search = mysqli_real_escape_string(
           $conn,
           // Match beginning of word boundary
           "[[:<:]]".
           // Replace space characters with regular expression
           // to match one or more space characters in the target field
           implode("[[.space.]]+",             
              preg_split("/\s+/", 
                 // Quote regular expression characters
                 preg_quote(trim($requestData['search']['value']))
              )
           ).
           // Match end of word boundary
           "[[:>:]]"
        );
    
    
        $sql.=" AND ( app_id REGEXP '$search' ";    
        $sql.=" OR fullname REGEXP '$search' ";
        $sql.=" OR contact REGEXP '$search' ";
        $sql.=" OR address REGEXP '$search' ";
        $sql.=" OR photo REGEXP '$search' ";
        $sql.=" OR datereg REGEXP '$search' )";
    }
    

    您也可以考虑使用full-text search

    【讨论】:

    • 说得很好。谢谢@Gyrocode.com btw 是否可以忽略间距?如果我搜索 Garry Ves。它不会找到 Garry Ves。如果有 2 个空格。
    • @kimdecastro,我的代码中有一个错误,现在已更正,请重试。
    • 真是个天才。顺便说一句,如果您搜索 Peter Doe 会怎样。它将显示 Peter V. Doe。如果您输入确切的全名,我尝试了您的代码,它可以完美运行。
    • @kimdecastro,如果你搜索Peter Dow,它应该找不到Peter V. Dow,但是它会找到Peter DowDr. Peter DowPeter Dow Jr.为了找到Peter V. Dow或@ 987654335@必须更改代码。
    • 因为其他客户没有中间名首字母。顺便说一句,感谢您帮助我,感谢您的帮助。继续加油!!
    【解决方案3】:

    如果我理解正确 - 您指的是搜索是由搜索框中的 keyup 事件触发的。此 javascript 将允许用户输入一个单词,然后按 Enter 以执行搜索。

    这需要添加到包含数据表初始化代码的同一个 js 文件中,并在初始化代码之后:

    var oTable = $('#example').dataTable({
       ... yourdatatable init code
    
    // unbind the keyup event that triggers the search 
    $("#example_filter input").unbind();
    
    // use fnFilter() to perform the search when the `Return` key is pressed
    $("#example_filter input").keyup(function (e) {
         if (e.keyCode === 13) {
             oTable.fnFilter(this.value);
         }
    });
    

    这假定数据表 v1.9。如果您使用的是 1.10,则有一个 SO 答案 here 概述了修改

    工作版本 -> https://jsfiddle.net/markps/HEDvf/3225/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-23
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      相关资源
      最近更新 更多