I have a basic URL shortener script but I am having an issue. Each time I enter a new url to shorten the script just adds the next letter to the database (i.e. http://www.both.com/a then http://www.both.com/b then http://www.both.com/c etc). The problem is I don't want to people to be able to view those links by simply going in sequential order. How can I make it so each new url has a random 6 digit alpha and numerical name created? Also, I wanted to make the alpha both random upper and lower case.
<?php
require 'config.php';
header('Content-Type: text/plain;charset=UTF-8');
$url = isset($_GET['url']) ? urldecode(trim($_GET['url'])) : '';
if (in_array($url, array('', 'about:blank', 'undefined', 'http://localhost/'))) {
die('Enter a URL.');
}
if (strpos($url, SHORT_URL) === 0) {
die($url);
}
function nextLetter(&$str) {
$str = ('z' == $str ? 'a' : ++$str);
}
function getNextShortURL($s) {
$a = str_split($s);
$c = count($a);
if (preg_match('/^z*$/', $s)) { // string consists entirely of `z`
return str_repeat('a', $c + 1);
}
while ('z' == $a[--$c]) {
nextLetter($a[$c]);
}
nextLetter($a[$c]);
return implode($a);
}
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$db->set_charset('utf8mb4');
$url = $db->real_escape_string($url);
$result = $db->query('SELECT slug FROM redirect WHERE url = "' . $url . '" LIMIT 1');
if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL
die(SHORT_URL . $result->fetch_object()->slug);
} else {
$result = $db->query('SELECT slug, url FROM redirect ORDER BY date DESC, slug DESC LIMIT 1');
if ($result && $result->num_rows > 0) {
$slug = getNextShortURL($result->fetch_object()->slug);
if ($db->query('INSERT INTO redirect (slug, url, date, hits) VALUES ("' . $slug . '", "' . $url . '", NOW(), 0)')) {
header('HTTP/1.1 201 Created');
echo SHORT_URL . $slug;
$db->query('OPTIMIZE TABLE `redirect`');
}
}
}
?>
try something like this :
function generateString($length) {
$alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$alphabetLength = strlen($alphabet);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $alphabet[rand(0, $alphabetLength - 1)];
}
return $randomString;
}
$short = generateRandomString(6);
Related
I am trying to update an old vBulletin product and it keeps throwing an error for me.
Cannot use object of type mysqli_result as array in C:\wamp\www\mem_payment.php on line 124
Line 124:
$vbma->setCustomerNumber(unserialize($purchase['info']), $product['pur_group'], false, $userinfo);
Line 102 - 130
$purchase = $vbulletin->db->query_first("SELECT * FROM " . TABLE_PREFIX .
"ma_purchases WHERE id = '" . $id . "'");
$order = unserialize($purchase['order']);
if ($order[0] !== $vbulletin->GPC['business'])
{
$status_code = '503 Service Unavailable';
// Paypal likes to get told its message has been received
if (SAPI_NAME == 'cgi' or SAPI_NAME == 'cgi-fcgi')
{
header('Status: ' . $status_code);
}
else
{
header('HTTP/1.1 ' . $status_code);
}
}
unset($order[0]);
if ($purchase and !in_array($order[1], array('renew', 'upgrade')))
{
$product = $vbulletin->db->query_read("SELECT pur_group FROM " . TABLE_PREFIX .
"ma_products WHERE id = '" . $order[1] . "'");
$userinfo = fetch_userinfo($purchase['userid']);
$vbma->setCustomerNumber(unserialize($purchase['info']), $product['pur_group'], false,
$userinfo);
$rand = rand($vbulletin->options['memarea_numstart'], $vbulletin->options['memarea_numend']);
$licnum = substr(md5($prodid . rand(0, 20000) . $rand . $rand), 0, rand(10, $vbulletin->
options['memarea_custnumleng']));
$licensedm = datamanager_init('License', $vbulletin, ERRTYPE_ARRAY);
$licensedm->setr('userid', $userinfo['userid']);
I have been reading numerous questions regarding this error stating to essentially:
define your query
query your query
then associate the query
IE:
$query = "SELECT 1";
$result = $mysqli->query($query);
$followingdata = $result->fetch_assoc()
Almost all of the answers are along those lines, although I am failing to see where this needs to be done.
I'm not sure if it has anything to do with the function, but I will add that as well:
function setCustomerNumber($ma_info, $usergroup = '', $usevb = true, $userinfo = '')
{
if ($usevb == false)
{
$this->vbulletin->userinfo = &$userinfo;
}
$fcust = $this->fields['custnum'];
$fpass = $this->fields['mpassword'];
$finfo = $this->fields['info'];
$userdm = datamanager_init('User', $this->vbulletin, ERRTYPE_ARRAY);
$userinfo = fetch_userinfo($this->vbulletin->userinfo['userid']);
$userdm->set_existing($userinfo);
if (!$this->vbulletin->userinfo["$fcust"] and !$this->vbulletin->userinfo["$fpass"])
{
$rand = rand($this->vbulletin->options['memarea_numstart'], $this->vbulletin->
options['memarea_numend']);
$num = $this->vbulletin->options['custnum_prefix'] . substr(md5($rand), 0, $this->
vbulletin->options['memarea_custnumleng'] - strlen($this->vbulletin->options['custnum_prefix']));
$userdm->set($fcust, $num);
$pass = substr(md5(time() . $num . $rand . rand(0, 2000)), 0, $this->vbulletin->
options['memarea_custnumleng']);
$userdm->set($fpass, $pass);
$this->sendCustomerInfo($this->vbulletin->userinfo['userid'], $this->vbulletin->
userinfo['username'], $this->vbulletin->userinfo['email'], $num, $pass);
}
if ($usergroup or $usergroup !== '' or $usergroup !== '0')
{
if ($usergroup != $this->vbulletin->userinfo['usergroupid'])
{
$ma_info['oldgroup'] = $this->vbulletin->userinfo['usergroupid'];
$userdm->set('usergroupid', $usergroup);
}
}
if ($ma_info)
{
$ma_info = serialize($ma_info);
$userdm->set($finfo, $ma_info);
}
$userdm->pre_save();
if (count($userdm->errors) == 0)
{
$userdm->save();
return true;
}
else
{
var_dump($userdm->errors);
return false;
}
}
Why am I getting this error? In your answer could you please explain to me what needs to be changed.
query_read returns mysqli_result&, you need convert it to an array first.
$query_result = $vbulletin->db->query_read(...);
$product = $query_result->fetch_assoc();
I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!
I'm working on a script that checks if the url already exists in the database, and if yes adds an additional -1 or -2 etc etc at the end. I found this script
But it 'd need to to check it again after adding-1. Since it may be already existing. How can I do that? I tired i this way
$query = mysql_query("SELECT * FROM posts WHERE url='$url'");
while ( $query ) {
$result = mysql_fetch_assoc($query);
$url = $result['url'];
$urlnew = $result['url'];
$oldurl = $url;
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
$url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;
$first++;
}
$url = $urlnew;
}
The new code above works just fine. But it checks only once. How can I make it to check untill it dose not exists in the DB?
tried adding a new sql query at the bottom after $url -$urlnew but it only breaks the function.
EDIT
Here's the correct script :D
$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");
if ( $query ) {
while ( $result = mysql_fetch_assoc($query) ) {
$url = $result['url'];
$urlnew = $result['url'];
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;
$first++;
}
}
}
$url = $urlnew;
Your code is likely vulnerable to SQL Injection. You should consider using PDO or MySQLi instead.
Here's an example of how you could do so:
$url = 'www.example.com';
$i = 0;
$max_duplicates = 100;
$query = $pdo->prepare('SELECT COUNT(id) count FROM urls WHERE url=?');
while ($i++ < $max_duplicates) {
$result = $query->execute($url);
if (!$result->fetch(PDO::FETCH_OBJ)->count)
break;
if ($i == 1) {
$url = $url . '-1';
} else {
$n = $i > 10 ? 2 : 1;
$url = substr($url, -$n) . $i;
}
}
Here's what I used for my needs
function checkLink($link, $counter=1){
global $connect;
$newLink = $link;
do{
$checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
if(mysqli_num_rows($checkLink) > 0){
$newLink = $link.'-'.$counter;
$counter++;
} else {
break;
}
} while(1);
return $newLink;
}
$link = 'www.example.com';
$uniquelink = checkLink($link);
I have a simple task to do with PHP, but since I'm not familiar with Regular Expression or something... I have no clue what I'm going to do.
what I want is very simple actually...
let's say I have these variables :
$Email = 'john#example.com'; // output : ****#example.com
$Email2 = 'janedoe#example.com'; // output : *******#example.com
$Email3 = 'johndoe2012#example.com'; // output : ***********#example.com
$Phone = '0821212121'; // output : 082121**** << REPLACE LAST FOUR DIGIT WITH *
how to do this with PHP? thanks.
You'll need a specific function for each. For mails:
function hide_mail($email) {
$mail_segments = explode("#", $email);
$mail_segments[0] = str_repeat("*", strlen($mail_segments[0]));
return implode("#", $mail_segments);
}
echo hide_mail("example#gmail.com");
For phone numbers
function hide_phone($phone) {
return substr($phone, 0, -4) . "****";
}
echo hide_phone("1234567890");
And see? Not a single regular expression used. These functions don't check for validity though. You'll need to determine what kind of string is what, and call the appropriate function.
For e-mails, this function preserves first letter:
function hideEmail($email)
{
$parts = explode('#', $email);
return substr($parts[0], 0, min(1, strlen($parts[0])-1)) . str_repeat('*', max(1, strlen($parts[0]) - 1)) . '#' . $parts[1];
}
hideEmail('hello#domain.com'); // h****#domain.com
hideEmail('hi#domain.com'); // h*#domain.com
hideEmail('h#domain.com'); // *#domain.com
I tried for a single-regex solution but don't think it's possible due to the variable-length asterisks. Perhaps something like this:
function anonymiseString($str)
{
if(is_numeric($str))
{
$str = preg_replace('/^(\d*?)\d{4}$/', '$1****');
}
elseif(($until = strpos($str, '#')) !== false)
{
$str = str_repeat('*', $until) . substr($str, $until + 1);
}
return $str;
}
I create one function to do this, works fine for me. i hope help.
function ofuscaEmail($email, $domain_ = false){
$seg = explode('#', $email);
$user = '';
$domain = '';
if (strlen($seg[0]) > 3) {
$sub_seg = str_split($seg[0]);
$user .= $sub_seg[0].$sub_seg[1];
for ($i=2; $i < count($sub_seg)-1; $i++) {
if ($sub_seg[$i] == '.') {
$user .= '.';
}else if($sub_seg[$i] == '_'){
$user .= '_';
}else{
$user .= '*';
}
}
$user .= $sub_seg[count($sub_seg)-1];
}else{
$sub_seg = str_split($seg[0]);
$user .= $sub_seg[0];
for ($i=1; $i < count($sub_seg); $i++) {
$user .= ($sub_seg[$i] == '.') ? '.' : '*';
}
}
$sub_seg2 = str_split($seg[1]);
$domain .= $sub_seg2[0];
for ($i=1; $i < count($sub_seg2)-2; $i++) {
$domain .= ($sub_seg2[$i] == '.') ? '.' : '*';
}
$domain .= $sub_seg2[count($sub_seg2)-2].$sub_seg2[count($sub_seg2)-1];
return ($domain_ == false) ? $user.'#'.$seg[1] : $user.'#'.$domain ;
}
Output: a******#gmail.com
$email = str_replace(substr($old_email, 1, strlen(explode("#", $old_email)[0])-1), "**********", $old_email);
This is a quick fix to the question above;
It ensures just the first character of the email address as the extension shows up.
You can increase or reduce the number of asterisks depending
I am trying to get the integrated search toolbars working on my page, however I am not having any luck. The regular search function is working for me, but whenever I type anything into the integrated toolbars, it returns 0 results.
Here is my jquery:
$("#parts_table").jqGrid({
url:'testparts2.php',
datatype: "json",
colNames:['Part ID','Name', 'Description', 'Weight'],
colModel:[
{name:'part_ID',index:'part_ID', search: true, stype:'text', width:55},
{name:'part_name',index:'part_name', width:90},
{name:'part_desc',index:'part_desc', width:100},
{name:'part_weight',index:'part_weight', width:80, align:"right"},
],
rowNum:30,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'part_ID',
viewrecords: true,
sortorder: "asc",
caption:"Parts in Database",
width: '800',
height: '300',
});
$("#parts_table").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});
$("#parts_table").jqGrid('filterToolbar',{stringResult: false,searchOnEnter : false, defaultSearch: 'cn', ignoreCase: true});
and here is my PHP code:
<?php
include "begin.php";
$page = $_REQUEST['page']; // get the requested page
$limit = $_REQUEST['rows']; // get how many rows we want to have into the grid
$sidx = $_REQUEST['sidx']; // get index row - i.e. user click to sort
$sord = $_REQUEST['sord']; // get the direction
if(!$sidx) $sidx =1;
//array to translate the search type
$ops = array(
'eq'=>'=', //equal
'ne'=>'<>',//not equal
'lt'=>'<', //less than
'le'=>'<=',//less than or equal
'gt'=>'>', //greater than
'ge'=>'>=',//greater than or equal
'bw'=>'LIKE', //begins with
'bn'=>'NOT LIKE', //doesn't begin with
'in'=>'LIKE', //is in
'ni'=>'NOT LIKE', //is not in
'ew'=>'LIKE', //ends with
'en'=>'NOT LIKE', //doesn't end with
'cn'=>'LIKE', // contains
'nc'=>'NOT LIKE' //doesn't contain
);
function getWhereClause($col, $oper, $val){
global $ops;
if($oper == 'bw' || $oper == 'bn') $val .= '%';
if($oper == 'ew' || $oper == 'en' ) $val = '%'.$val;
if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%';
return " WHERE $col {$ops[$oper]} '$val' ";
}
$where = ""; //if there is no search request sent by jqgrid, $where should be empty
$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : false;
$searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: false;
$searchString = isset($_GET['searchString']) ? $_GET['searchString'] : false;
if ($_GET['_search'] == 'true') {
$where = getWhereClause($searchField,$searchOper,$searchString);
}
$totalrows = isset($_REQUEST['totalrows']) ? $_REQUEST['totalrows']: false;
if($totalrows) {
$limit = $totalrows;
}
$result = mysql_query("SELECT COUNT(*) AS count FROM parts");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * FROM parts ".$where." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$response->rows[$i]['part_ID']=$row[part_ID];
$response->rows[$i]['cell']=array($row[part_ID],$row[part_name],$row[part_desc],$row[part_weight]);
$i++;
}
echo json_encode($response);
?>
It took me hours of searching to find a PHP example that worked for regular searching (see above), however it doesn't seem to work for the toolbar searching. Can anyone help? Thanks
edit: Here is code from jqGrid's demo folder for using this search, but it appears to be full of errors and I have no idea how to use it for my case. I don't need to specify data type for the searches (they are all varchars, so strings will work fine)..so I think that I can strip out the switch/case part for value conversion. I think I just need to change my original code to use $_REQUEST['filters'] and a foreach loop to build the query, but I'm not that great with PHP so any help is appreciated.
demo code:
$wh = "";
$searchOn = Strip($_REQUEST['_search']);
if($searchOn=='true') {
$searchstr = Strip($_REQUEST['filters']);
$wh= constructWhere($searchstr);
//echo $wh;
}
function constructWhere($s){
$qwery = "";
//['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
$qopers = array(
'eq'=>" = ",
'ne'=>" <> ",
'lt'=>" < ",
'le'=>" <= ",
'gt'=>" > ",
'ge'=>" >= ",
'bw'=>" LIKE ",
'bn'=>" NOT LIKE ",
'in'=>" IN ",
'ni'=>" NOT IN ",
'ew'=>" LIKE ",
'en'=>" NOT LIKE ",
'cn'=>" LIKE " ,
'nc'=>" NOT LIKE " );
if ($s) {
$jsona = json_decode($s,true);
if(is_array($jsona)){
$gopr = $jsona['groupOp'];
$rules = $jsona['rules'];
$i =0;
foreach($rules as $key=>$val) {
$field = $val['field'];
$op = $val['op'];
$v = $val['data'];
if($v && $op) {
$i++;
// ToSql in this case is absolutley needed
$v = ToSql($field,$op,$v);
if ($i == 1) $qwery = " AND ";
else $qwery .= " " .$gopr." ";
switch ($op) {
// in need other thing
case 'in' :
case 'ni' :
$qwery .= $field.$qopers[$op]." (".$v.")";
break;
default:
$qwery .= $field.$qopers[$op].$v;
}
}
}
}
}
return $qwery;
}
function ToSql ($field, $oper, $val) {
// we need here more advanced checking using the type of the field - i.e. integer, string, float
switch ($field) {
case 'id':
return intval($val);
break;
case 'amount':
case 'tax':
case 'total':
return floatval($val);
break;
default :
//mysql_real_escape_string is better
if($oper=='bw' || $oper=='bn') return "'" . addslashes($val) . "%'";
else if ($oper=='ew' || $oper=='en') return "'%" . addcslashes($val) . "'";
else if ($oper=='cn' || $oper=='nc') return "'%" . addslashes($val) . "%'";
else return "'" . addslashes($val) . "'";
}
}
$result = mysql_query("SELECT COUNT(*) AS count FROM invheader a, clients b WHERE a.client_id=b.client_id".$wh);
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT a.id, a.invdate, b.name, a.amount,a.tax,a.total,a.note FROM invheader a, clients b WHERE a.client_id=b.client_id".$wh." ORDER BY ".$sidx." ".$sord. " LIMIT ".$start." , ".$limit;
$result = mysql_query( $SQL ) or die("Could not execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$responce->rows[$i]['id']=$row[id];
$responce->rows[$i]['cell']=array($row[id],$row[invdate],$row[name],$row[amount],$row[tax],$row[total],$row[note]);
$i++;
}
//echo $json->encode($responce); // coment if php 5
echo json_encode($responce);
I actually just had this same problem myself yesterday. You are correct, you need to bring in the filters using $_REQUEST['filters'] and then break it up so that you can use each piece.
First, you are going to need to set stringResult: true in your jQuery file where you initialize the FilterToolbar.
Here is the code that PHP will use to bring in, and break up the filters object:
// Gets the 'filters' object from JSON
$filterResultsJSON = json_decode($_REQUEST['filters']);
// Converts the 'filters' object into a workable Array
$filterArray = get_object_vars($filterResultsJSON);
Now that you have $filterArray containing the contents of the filters object, you can now break up the rules object which is contained inside. Basically, there is another array inside the $filterArray which contains the search details if the user tries performing this search across multiple columns in their table - it's called rules.
Here is how I break up the rules object and perform a SELECT query based on the user's input:
// Begin the select statement by selecting cols from tbl
$sql = 'select '.implode(',',$crudColumns).' from '.$crudTableName;
// Init counter to 0
$counter = 0;
// Loop through the $filterArray until we process each 'rule' array inside
while($counter < count($filterArray['rules']))
{
// Convert the each 'rules' object into a workable Array
$filterRules = get_object_vars($filterArray['rules'][$counter]);
// If this is the first pass, start with the WHERE clause
if($counter == 0){
$sql .= ' WHERE ' . $filterRules['field'] . ' LIKE "%' . $filterRules['data'] . '%"';
}
// If this is the second or > pass, use AND
else {
$sql .= ' AND ' . $filterRules['field'] . ' LIKE "%' . $filterRules['data'] . '%"';
}
$counter++;
}
// Finish off the select statement
$sql .= ' ORDER BY ' . $postConfig['sortColumn'] . ' ' . $postConfig['sortOrder'];
$sql .= ' LIMIT '.$intStart.','.$intLimit;
/* run the query */
$result = mysql_query( $sql )
I'm sure you'll have questions, so feel free to ask if you do!