Here's a code snippet for PHP for building SQL an search query (where clause) from the jqGRID params.
I'm not sure if this is the best/most efficient way to do this, but since I couldn't find code for doing this in the documentation anywhere, I'm posting what I'm doing.
I keep an array of the operators sent from jqGrid, and use a function to return the WHERE clause associated with it. I'm assuming that 'contains' and 'is in' mean the same thing, which is probably not what Tony meant. It's easy to change the mapping though, so feel free to do so.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
$ops = array(<br /> 'eq'=>'=', //equal<br /> 'ne'=>'<>',//not equal<br /> 'lt'=>'<', //less than<br /> 'le'=>'<=',//less than or equal<br /> 'gt'=>'>', //greater than<br /> 'ge'=>'>=',//greater than or equal<br /> 'bw'=>'LIKE', //begins with<br /> 'bn'=>'NOT LIKE', //doesn't begin with<br /> 'in'=>'LIKE', //is in<br /> 'ni'=>'NOT LIKE', //is not in<br /> 'ew'=>'LIKE', //ends with<br /> 'en'=>'NOT LIKE', //doesn't end with<br /> 'cn'=>'LIKE', // contains<br /> 'nc'=>'NOT LIKE' //doesn't contain<br /> );<br /> /**<br /> * Returns SQL WHERE clause<br /> * @param string $col sql column name<br /> * @param string $oper operator from jqGrid<br /> * @param string $val value (right hand side)<br /> */<br /> function getWhereClause($col, $oper, $val){<br /> global $ops;<br /> if($oper == 'bw' || $oper == 'bn') $val .= '%';<br /> if($oper == 'ew' || $oper == 'en' ) $val = '%'.$val;<br /> if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%';<br /> return " AND $col {$ops[$oper]} '$val' ";<br /> }<br /> <br /> |
Obviously, you'll need to get the search params from the $_GET array. I do something like this:
|
1 2 3 |
$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : false;<br /> $searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: false;<br /> $searchString = isset($_GET['searchString']) ? $_GET['searchString'] : false;<br /> |
Then the query is simply: “SELECT * FROM $searchField “. getWhereClause($searchField,$searchOper,$searchString);
-paul
Copyright 2014 TriRand LtdAll Rights ReservedRSS
Back to Top