2012-09-16 2 views
0

jqGrid의 단일 검색 기능은 어떻게 사용합니까?jqGrid : 단일 검색 기능을 사용하는 방법?

Im "버전 3.7의 새로운 기능"에서 "단일 검색"예제를 따른다. jqGrid Demo Page

내 스크립트는 데이터베이스에서 데이터를 검색하는 데 사용되는 쿼리를 저장하지만 스크립트는 필터링을 수행하지 않습니다.

누구든지 PHP를 사용하여 단일 검색 기능의 전체 예제를 가르쳐 줄 수 있습니까?

또한 데모 페이지의 스크립트와 관련하여 질문이 있습니다.

  1. jQuery는 결과를 필터링하기 위해 PHP에 조건을 어떻게 전달합니까? 쿼리에서 변수가 $where이지만 PHP 스크립트에서 변수가 선언되지 않았다는 것을 알았습니다.

답변

3

나는 MySQL 데이터베이스를 사용하여 예제를 만들었습니다. 모든
먼저 몇 가지 기록을 "테스트"데이터베이스에 "항목"테이블을 생성, 삽입 :

CREATE DATABASE IF NOT EXISTS test; 

CREATE TABLE IF NOT EXISTS `items` (
    `item_id` int(11) NOT NULL, 
    `item` varchar(255) DEFAULT '', 
    `item_cd` varchar(255) DEFAULT '', 
    PRIMARY KEY (`item_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

LOCK TABLES `items` WRITE; 
INSERT INTO `items` VALUES (1,'Lorem','575878'); 
INSERT INTO `items` VALUES (2,'Lorem','857450'); 
INSERT INTO `items` VALUES (3,'ipsum','292404'); 
INSERT INTO `items` VALUES (4,'dolor','814131'); 
INSERT INTO `items` VALUES (5,'sit','962077'); 
INSERT INTO `items` VALUES (6,'amet,','549801'); 
INSERT INTO `items` VALUES (7,'sed','166822'); 
INSERT INTO `items` VALUES (8,'in','616758'); 
INSERT INTO `items` VALUES (9,'id','550799'); 
INSERT INTO `items` VALUES (10,'dictum','763004'); 
INSERT INTO `items` VALUES (11,'velit','244985'); 
INSERT INTO `items` VALUES (12,'est','525127'); 
INSERT INTO `items` VALUES (13,'suspendisse,','351690'); 
INSERT INTO `items` VALUES (14,'mauris','655061'); 
INSERT INTO `items` VALUES (15,'eget','423779'); 
INSERT INTO `items` VALUES (16,'imperdiet','493615'); 
INSERT INTO `items` VALUES (17,'ut,','864029'); 
INSERT INTO `items` VALUES (18,'mauris','546065'); 
INSERT INTO `items` VALUES (19,'vestibulum,','562819'); 
INSERT INTO `items` VALUES (20,'sagittis','238043'); 
INSERT INTO `items` VALUES (21,'ac.','867508'); 
INSERT INTO `items` VALUES (22,'Mauris','674897'); 
INSERT INTO `items` VALUES (23,'id','288097'); 
INSERT INTO `items` VALUES (24,'quam,','889530'); 
UNLOCK TABLES; 

다음, HTML 페이지를 생성 "singlesearch.html"

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <link rel="stylesheet" type="text/css" media="screen" href="http://www.trirand.com/blog/jqgrid/themes/redmond/jquery-ui-custom.css" /> 
    <link rel="stylesheet" type="text/css" media="screen" href="http://www.trirand.com/blog/jqgrid/themes/ui.jqgrid.css" /> 
    <script src="http://www.trirand.com/blog/jqgrid/js/jquery.js" type="text/javascript"></script> 
    <script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script> 
    <script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
    jQuery(document).ready(function(){ 
     jQuery("#single").jqGrid({ 
      url:'localset.php', 
      datatype: "json", 
      height: 255, 
      width: 600, 
      colNames:['Index','Name', 'Code'], 
      colModel:[ 
       {name:'item_id',index:'item_id', width:65, sorttype:'int'}, 
       {name:'item' ,index:'item' , width:150}, 
       {name:'item_cd',index:'item_cd', width:100} 
      ], 
      rowNum:50, 
      rowTotal: 2000, 
      rowList : [20,30,50], 
      loadonce: false, 
      mtype: "GET", 
      rownumbers: true, 
      rownumWidth: 40, 
      gridview: true, 
      pager: '#psingle', 
      sortname: 'item_id', 
      viewrecords: true, 
      sortorder: "asc", 
      caption: "Single search on local data", 
      loadError: function(jqXHR, textStatus, errorThrown) { 
       /* 
       alert('HTTP status code: ' + jqXHR.status + '\n' + 
         'textStatus: ' + textStatus + '\n' + 
         'errorThrown: ' + errorThrown); 
       alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText); 
       */ 
       alert(jqXHR.responseText); 
      } 
     }); 

     jQuery("#single").jqGrid(
      'navGrid', 
      '#psingle', 
      {del:false,add:false,edit:false}, 
      {},      // default settings for edit 
      {},      // default settings for add 
      {},      // 
      {closeAfterSearch:true}, // search options 
      {}       // view parameters 
     ); 
    }); 
    </script> 
</head> 
<body> 
    <table id="single"></table> 
    <div id="psingle"></div> 
</body> 
</html> 

<?php 

function myTrace($str) { 
    // Adjust the log file name before uncommenting 
    //@file_put_contents("/tmp/localset.log", $str."\n", FILE_APPEND); 
} 

myTrace(print_r($_REQUEST,true)); 

// connect to the database 
$link = mysqli_init(); 

// Adjust host, user, password and dbname before use! 
$db = mysqli_real_connect($link, "myhost", "myuser", "mypass", "test"); 
if (!$db) { 
    die('Connect Error ('.mysqli_connect_errno().'): '.mysqli_connect_error()); 
} 

mysqli_set_charset($link, "utf8"); 

$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;   // get the requested page 
$limit = isset($_REQUEST['rows']) ? $_REQUEST['rows'] : 50;   // get how many rows we want to have into the grid 
$sidx = isset($_REQUEST['sidx']) ? $_REQUEST['sidx'] : 1;   // get index row - i.e. user click to sort 
$sord = isset($_REQUEST['sord']) ? $_REQUEST['sord'] : "asc";  // get the direction 

if ($_REQUEST["_search"] == "false") { 
    $where = "where 1"; 
} else { 
    $operations = array(
     'eq' => "= '%s'",   // Equal 
     'ne' => "<> '%s'",   // Not equal 
     'lt' => "< '%s'",   // Less than 
     'le' => "<= '%s'",   // Less than or equal 
     'gt' => "> '%s'",   // Greater than 
     'ge' => ">= '%s'",   // Greater or equal 
     'bw' => "like '%s%%'",  // Begins With 
     'bn' => "not like '%s%%'", // Does not begin with 
     'in' => "in ('%s')",   // In 
     'ni' => "not in ('%s')",  // Not in 
     'ew' => "like '%%%s'",  // Ends with 
     'en' => "not like '%%%s'", // Does not end with 
     'cn' => "like '%%%s%%'",  // Contains 
     'nc' => "not like '%%%s%%'", // Does not contain 
     'nu' => "is null",   // Is null 
     'nn' => "is not null"  // Is not null 
    ); 
    $value = mysqli_real_escape_string($link, $_REQUEST["searchString"]); 
    $where = sprintf("where %s ".$operations[$_REQUEST["searchOper"]], $_REQUEST["searchField"], $value); 
} 

$SQL = "SELECT item_id, item, item_cd FROM items ".$where." ORDER BY $sidx $sord"; 
myTrace($SQL); 
$result = mysqli_query($link, $SQL); 
if (!$result) { 
    myTrace(mysqli_error($link)); 
    die("Couldn't execute query: ".mysqli_error($link)); 
} 

if ($limit < 0) $limit = 0; 

$start = ($limit * $page) - $limit; 
if ($start < 0) $start = 0; 

$count = mysqli_num_rows($result); 
if ($count > 0) { 
    $total_pages = ceil($count/$limit); 
} else { 
    $total_pages = 0; 
} 

if ($page > $total_pages) { 
    $page = $total_pages; 
} 

$responce->page = $page; 
$responce->total = $total_pages; 
$responce->records = $count; 

mysqli_data_seek($result, $start); 
for ($i = 0; $row = mysqli_fetch_assoc($result); $i++) { 
    if (($limit > 0) && ($i >= $limit)) break; 
    $responce->rows[$i]['id'] = $row['item_id']; 
    $responce->rows[$i]['cell'] = array($row['item_id'], $row['item'], $row['item_cd']); 
} 
echo json_encode($responce); 

mysqli_close($link); 

?> 

이 P에 PHP mysqli extension을 사용 :

그런 다음 "localset.php의"PHP 페이지를 만들 HP.INI 파일에서 "localset.php"스크립트 (15 행)에서 연결 매개 변수를 조정하고 마지막으로 브라우저에서 "singlesearch.html"페이지를 엽니 다.

+0

답장을 보내 주셔서 감사합니다. 몇 가지 질문이 있습니다. 1. jQuery는 _search, searchString 및 search Oper의 값을 어디에서 얻습니까? 2. % s의 의미는 무엇입니까? – JohnSmith

+0

_search, searchString 및 searchOper 매개 변수에 대한 설명은 [이 페이지] (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching)를 참조하십시오. "% s"은 [PHP sprintf] (http://php.net/manual/en/function.sprintf.php) 함수를 사용하여 문자열을 인쇄하기위한 자리 표시 자입니다. –