PHP Pagination values errors - php

I get errors:
Notice: Undefined index: p, page, srt and where
// set default pagenation values
if(!$_GET['p']) $_GET['p'] = $conf['perpage']; // default number of entries per page
if(!$_GET['page']) $_GET['page'] = 1; // current page
if(!$_GET['srt']) $_GET['srt'] = $conf['srt']; // default sort order
$start = ($_GET['page'] - 1) * $_GET['p']; // start row for query
// get total number of entries for pagenation
$result = mysql_query("SELECT COUNT(*) FROM articals $where", $link);
$total = mysql_fetch_array($result); $total = $total[0]; // total number of listings
$pages = ceil($total / $_GET['p']); // number of pages
And also on:
Notice: Undefined index: category, description,model,cond,location,photos,featured and where
$_GET = safe_data($_GET, 'query');
if($_GET['category']) $where .= "AND (category='$_GET[category]' OR category2='$_GET[category]') ";
if($_GET['description']) $where .= "AND description LIKE '%$_GET[description]%' ";
if($_GET['model']) $where .= "AND model LIKE '%$_GET[model]%' ";
if($_GET['cond']) $where .= "AND cond='$_GET[cond]' ";
if($_GET['location']) $where .= "AND location='$_GET[location]' ";
if($_GET['photos']) $where .= "AND images>'0' ";
if($_GET['featured']) $where .= "AND featured='1' ";
// finialize query string if necessary
if(substr($where, 0, 3) == 'AND') {
$where = ltrim($where, 'AND');
$where = 'WHERE'.$where;
}
// do not show hidden and expired listings
$display = "hide!='1' AND (expire>'".time()."' OR expire='' OR expire='0') AND (user_expire>'".time()."' OR user_expire='' OR user_expire='0')";
$display = "hide!='1'";
if(!$where) $where = "WHERE ".$display;
else $where .= "AND ".$display;
Any Help please?

You have to wrap isset() Around every get request to get rid of the notice.
The Notice is shown because their is no value.
You can use it like this: if(isset($_GET['p']))

This code might help you, it wraps the http php response:
class Input {
public static function Post($item,$default=null){
//If the value was posted, then return that value, else return the $default value.
return isset($_POST[$item]) ? $_POST[$item] : $default;
}
public static function Get($item,$default=null){
return isset($_GET[$item]) ? $_GET[$item] : $default;
}
public static function Cookie($item,$default=null){
return isset($_COOKIE[$item]) ? $_COOKIE[$item] : $default;
}
public static function Param($item,$default=null){
return self::Post($item) ?: self::Get($item) ?: self::Cookie($item) ?: $default;
}
}
usage:
Input::Get('p',$conf['perpage']); // First argument is the index, second is default if not set.
in your example:
$p = Input::Get('p',$conf['perpage']);
$page = Input::Get('page',1);
$srt= Input::Get('page',$conf['srt']);
$start = ($page - 1) *$p; // start row for query

In your URL, do you have parameters such as http://www.yoursite.com/yourpage.php?p=XXX&page=YYYY&srt=ZZZZ ?
If those parameters are optionnal, use:
if (!isset($_GET["p"])) $_GET["p"] = $conf["perpage"];
But actually, a better practice is to not assign $_GET by yourself. Instead, set a variable and use it later instead of using $_GET content:
$p = (isset($_GET["p"])?$_GET["p"]:$conf["perpage"]);
If you are doing a redirection in your htaccess, make sure to forward the GET parameters using [QSA].

Related

If condition A execute 1 OR if condition B execute 2 return not as expected

status stored has value 'LET, SALE, LET/SALE'
My php code does not return as expected, I wish if ($input['status'] = "SALE") will return 'SALE, LET/SALE' but it return only LET/SALE
I have tried to amend the code many ways, but can't work probably
if (!empty($input['status']))
{
{
if ($input['status'] = "SALE");
{
if (is_null($where))
{
$where = "WHERE";
}
else {
$where = "AND";
}
$query .= " $where status LIKE '%".$input['status']."%' AND `selling` <=
{$input['max_price']}";
}
}
{
if ($input['status'] = "LET");
{
if (is_null($where))
{
$where = "WHERE";
}
else {
$where = "AND";
}
$query .= " $where status LIKE '%".$input['status']."%' AND `rental` <=
{$input['max_price']}";
}
}
}
I wish to query property LET or SALE at condition max_price. Lets say if query SALE with max 100,000 return results shall include SALE, LET/SALE with max_price less than 100,000
You are assigning a value in your "if" statement. Use == (is equal to) instead of = (equals). What's happening is that it reassigns the value each time and stays at the last choice, which was LET/SALE
Change to:
if ($input['status'] == "SALE");
and do that for all of your "ifs"

Codeigniter returns wrong "pagination" results

I have this helper method which job should be to prepare pagination data in order to retrieve it on controller...
Basically this is the code which happens in helper
if (!isset($_GET['page'])) {
$_GET['page'] = 1;
}
if (!isset($_GET['per_page'])) {
$_GET['per_page'] = 5;
}
$results = $ci->$model->get('', $_GET['per_page'], $_GET['page']);
And this is my model which should return data
public function get($tableName = "", $limit = null, $start = null)
{
if ($tableName == "") {
$tableName = $this->table;
}
if ($limit != null && $start != null) {
// problem is here with limit and start which returns wrong data
$this->db->limit($limit, $start);
$query = $this->db->get($tableName);
var_dump($query->result());
die();
}
} else {
$query = $this->db->get($tableName);
}
return $query->result();
}
Problem is that data returned from model isn't correct and i can't figure out how to get properly data based on page number and items per page....
So in my case if i request data with paramas $_GET['page'] = 1 and $_GET['per_page'] = 5 it will return 5 records, but starting with record 2 till record 6. So my question is how to properly request give me let say 5 records on starting page 1 and then give me another 5 records on page 2 ETC....
If you need any additional information please let me know and i will provide. Thank you
The problem lies within your $start variable. You should remember that when using getting the first the 5 records, you should use an offset 0 instead 1. Counting starts from 0 remember :)
The code should be
public function get($tableName = "", $limit = null, $start = null)
{
if ($tableName == "") {
$tableName = $this->table;
}
if ($limit != null && $start != null) {
// problem is here with limit and start which returns wrong data
//$this->db->limit($limit, $start);
// use this instead
$this->db->limit($limit, ( $start - 1 ) * $limit );
$query = $this->db->get($tableName);
var_dump($query->result());
die();
}
} else {
$query = $this->db->get($tableName);
}
return $query->result();
}
This is working example try to do like this: https://www.formget.com/pagination-in-codeigniter/

Check NULL value using PhpActiveRecord

According to the documentation here (http://www.phpactiverecord.org/projects/main/wiki/Finders)
There is a way to find records in the database like so below.
# fetch all lousy romance novels which are cheap
Book::all(array('conditions' => array('genre = ? AND price < ?', 'Romance', 15.00)));
# sql => SELECT * FROM `books` WHERE genre = 'Romance' AND price < 15.00
This however will not work if any of the values are NULL. This is simply because NULL is not any value so it does not have anything to compare from. This I understand, but what I can't figure out in the documentation is how to actually check using that format if the value is null or not.
In SQL you could simply say WHERE value is null, or not null, but with PHPActiveRecord condition array string I'm not sure...
The reason I want to do it with the condition string and array is I have code setup which automatically creates those conditions, I'll post the code below.
function create_find_options($fields,$operators,$values,$sortfields,$sortdirections,$limit,$offset,$logic){
$conditionstring = '';
$fieldcount = count($fields);
$i=0;
for($k=0;$k<count($logic)-1;$k++){
$conditionstring.="(";//add starting parenthesis for every known logic.
}
for($i=0;$i<$fieldcount;$i++){
$conditionstring.=$fields[$i];
switch($operators[$i]){
case "equals":
$conditionstring.=" = ?";
break;
case "greaterthan":
$conditionstring.=" > ?";
break;
case "lessthan":
$conditionstring.=" < ?";
break;
case "notequals":
$conditionstring.=" != ?";
break;
case "contains":
$conditionstring.=" LIKE ?";
break;
}
if($i!=$fieldcount-1 && $fieldcount>=2){
if($i>0){
$conditionstring.=")";//first condition does not get ending parenthesis.
}
$conditionstring.=" ".$logic[$i]." ";//AND or OR
}
}
//$conditionstring = substr($conditionstring,0,strlen($conditionstring)-5);
//die($conditionstring);
$options = array('conditions' => array($conditionstring));
$i=0;
for($i=0;$i<$fieldcount;$i++){
if($operators[$i]=="contains"){ //exception for contains because it needs the percentage symbols around the value.
$options['conditions'][] = "%".$values[$i]."%";
}else{
$options['conditions'][] = $values[$i];
}
}
//Add any sorts now.
$i=0;
$sortcount = count($sortfields);
$orderstring = '';
for($i=0;$i<$sortcount;$i++){
$orderstring.= $sortfields[$i]." ".$sortdirections[$i].",";
}
$orderstring = rtrim($orderstring,",");//remove trailing comma
$options['order'] = $orderstring;//sets order rules.
//Add any limits now.
if(isset($limit)){
$options['limit'] = $limit;
}
if(isset($offset)){
$options['offset'] = $offset;
}
return $options;
}
So my function will automatically create the condition string needed, but it fails on NULL for the reason I described above. I think I need to add some extra conditions in here that if I detect NULL how to handle it better, but I'm not sure how to do that or if that's possible with PHPActiveRecord?
Well after spending ... all day, I have found a solution. I suppose it might have been common sense but it was not in the documentation so I had to guess.
Apparently you can simply say 'is null' in the condition string like regular SQL and it will work...
That said I updated my function to the following and this generate a complete options array with the conditions ready to go that will work even with null values.
Hopefully this is useful to someone! In my situation I wanted 0 to be the same as null, so you can adjust accordingly for your situation.
function create_find_options($fields,$operators,$values,$sortfields,$sortdirections,$limit,$offset,$logic){
$conditionstring = '';
$fieldcount = count($fields);
$i=0;
for($k=0;$k<count($logic)-1;$k++){
$conditionstring.="(";//add starting parenthesis for every known logic.
}
for($i=0;$i<$fieldcount;$i++){
$conditionstring.=$fields[$i];
$nullFound = false;
if($values[$i]=='0'){
$nullFound = true;
}
switch($operators[$i]){
case "equals":
if($nullFound==true){
$conditionstring.=" is null OR ".$fields[$i].' = 0';
}else{
$conditionstring.=" = ?";
}
break;
case "greaterthan":
$conditionstring.=" > ?";
break;
case "lessthan":
$conditionstring.=" < ?";
break;
case "notequals":
if($nullFound==true){
$conditionstring.=" is not null OR ".$fields[$i].' != 0';
}else{
$conditionstring.=" != ? OR ".$fields[$i].' is null';
}
break;
case "contains":
$conditionstring.=" LIKE ?";
break;
}
if($i!=$fieldcount-1 && $fieldcount>=2){
if($i>0){
$conditionstring.=")";//first condition does not get ending parenthesis.
}
$conditionstring.=" ".$logic[$i]." ";//AND or OR
}
}
//$conditionstring = substr($conditionstring,0,strlen($conditionstring)-5);
//die($conditionstring);
$options = array('conditions' => array($conditionstring));
$i=0;
for($i=0;$i<$fieldcount;$i++){
if($values[$i]!="0"){
if($operators[$i]=="contains"){ //exception for contains because it needs the percentage symbols around the value.
$options['conditions'][] = "%".$values[$i]."%";
}else{
$options['conditions'][] = $values[$i];
}
}
}
//Add any sorts now.
$i=0;
$sortcount = count($sortfields);
$orderstring = '';
for($i=0;$i<$sortcount;$i++){
$orderstring.= $sortfields[$i]." ".$sortdirections[$i].",";
}
$orderstring = rtrim($orderstring,",");//remove trailing comma
$options['order'] = $orderstring;//sets order rules.
//Add any limits now.
if(isset($limit)){
$options['limit'] = $limit;
}
if(isset($offset)){
$options['offset'] = $offset;
}
//die(print_r($options));
return $options;
}

I need a character or string which will match ANY value in my table field

I have a form that requires the user to only fill out at least 1 (out of four) fields. They can then submit and get a search result based off of their input.
The problem is, I can't get a character to set my variables to that will match any database value. Here is my code for some context;
if (isset($_POST['buildname']) ||
isset($_POST['weapon']) ||
isset($_POST['category']) ||
isset($_POST['id']))
{
if ($_POST['buildname'] == "")
{
$buildname = ".*";
}
if ($_POST['weapon'] == "")
{
$weapon = ".*";
}
if ($_POST['category'] == "")
{
$category = ".*";
}
if ($_POST['id'] == "")
{
$id = ".*";
}
$buildname = sanitizeString($_POST['buildname']);
$weapon = ($_POST['weapon']);
$category = ($_POST['category']);
$id = ($_POST['id']);
$searchstring = "SELECT buildname,weapon,category,id,author FROM weapons " .
"WHERE buildname='$buildname' AND weapon='$weapon' AND category='$category' AND id='$id'";
As you can see, the code looks at if one of the variables is set, then submits a form. If a variable isn't set, it assigns a character of ".*" (which I thought would match anything). It then queries the database to match any rows. I get no results unless I enter EVERY field with a correct entry.
Any ideas?
Thanks!
I would not use %, instead do something like this
if (isset($_POST['buildname']) || isset($_POST['weapon']) || isset($_POST['category']) || isset($_POST['id'])){
$sqlArray = array();
if(isset($_POST['buildname'])){
$sqlArray[] = "buildname='" . mysqli_real_escape_string($connection,$_POST['buildname']) . "'";
}
if(isset($_POST['weapon'])){
$sqlArray[] = "weapon='" . mysqli_real_escape_string($connection,$_POST['weapon']) . "'";
}
if(isset($_POST['category'])){
$sqlArray[] = "category='" . mysqli_real_escape_string($connection,$_POST['category']) . "'";
}
if(isset($_POST['id'])){
$sqlArray[] = "id='" . mysqli_real_escape_string($connection,$_POST['id']) . "'";
}
$searchstring = "SELECT buildname,weapon,category,id,author FROM weapons " .
"WHERE " . implode(' AND ', $sqlArray);
}
The wildcard character for MySQL is: %
The query you are executing, you "thought would match anything" wont. The statement uses no regular expressions.
WHERE buildname='$buildname' AND weapon='$weapon'
Which is essentially saying you need to have the following fields equal their string value of:
WHERE buildname='.*' AND weapon='.*'
I doubt you have any building with a name of .*.
It would be better to not filter on that field. basically remove the WHERE cause criteria if the variable is not defined.
You can do this dynamically, buliding the SQL statement only when you need to filter by that field.
if (isset($_POST['somevalue']) && ! empty($_POST['somevalue'])) {
$where .= 'column_name = ?';
$values[] = sanitizeString($_POST['somevalue]);
}
I've also used positional parameters which assumes you will be using the PDO or MySQLi libraries for querying.
No, you are using = operator, that only compares 2 values. In your case it will search for '.*' - and fail. If you want to ignore the fields, that were not filled, just don't put them into the query: no need for regexps. So, if the weapon and category are missing, your query should be like this
$searchstring = 'SELECT buildname,weapon,category,id,author FROM weapons WHERE ';
$fields = array('buildname', 'weapon', 'category', 'id');
$data = array();
foreach($fields as $value)
{
if (isset($_POST[$value]) && ($_POST[$value] != "") )
{
$data[] = sanitizeString($_POST[$value]);
}
}
$n = count($data);
if($n > 0)
{
$searchstring .= implode(' AND ', $data);
//do MySQL request and output result
}
Don't overcomplicate simple things. Also your code is vulnerable to SQL injection as some fields are not escaped.
You can do it like this:
$fields = array('buildname', 'weapon', 'category', 'id');
$sql = 'SELECT buildname, weapon, category, id, author FROM weapons';
$prefix = ' WHERE ';
foreach ($fields as $field) {
if (isset($_POST[$field]) && strlen($_POST[$field])>1) {
$sql .= $prefix . $field . '=\''
. sanitizeString($_POST[$field]) . '\'';
$prefix = ' AND ';
}
}
if ($prefix == ' AND ') {
// send the query
}
Notice: if you want to perform search with incomplete values, you could use LIKE instead of =, example:
$sql .= $prefix . $field . ' LIKE \'%' . sanitizeString($_POST[$field]) . '%\'';
But keep in mind that LIKE is slower than =

How to update a variable in a while loop that is used to nitiate the loop

am having a problem with a bit of code.
I am trying to generate a unique name to insert into a database.
i have created the following function which checks to see if the name already exists:
function checkExists($database_reelfilm, $reelfilm, $mySlug, $locVal){
$mmid_rs_slugCheck = "-1";
if (isset($mySlug)) {
$mmid_rs_slugCheck = $mySlug;
}
$mmid2_rs_slugCheck = "-1";
if (isset($locVal)) {
$mmid2_rs_slugCheck = $locVal;
}
mysql_select_db($database_reelfilm, $reelfilm);
$query_rs_slugCheck = sprintf("SELECT * FROM locations_loc WHERE locations_loc.slug_loc = %s AND locations_loc.id_loc != %s", GetSQLValueString($mmid_rs_slugCheck, "text"),GetSQLValueString($mmid2_rs_slugCheck, "int"));
$rs_slugCheck = mysql_query($query_rs_slugCheck, $reelfilm) or die(mysql_error());
$row_rs_slugCheck = mysql_fetch_assoc($rs_slugCheck);
$totalRows_rs_slugCheck = mysql_num_rows($rs_slugCheck);
if($totalRows_rs_SlugCheck > 0){
return true;
}else{
return false;
}
};
i then create a loop to checking if the variable name exists, if it does i want it to add the value of the counter to the variable name then recheck to see if that exists until i have a unique name which i can then save to my db.
$updateVal = slugify($row_rs_locations['name_loc']);
$newSlug = slugify($row_rs_locations['name_loc']);
$locVal = $row_rs_locations['id_loc'];
//echo(slugify($row_rs_locations['name_loc']));
$checkCount = 1;
$isDupe = '<BR>';
while(checkExists($database_reelfilm, $reelfilm, $newSlug, $locVal)){
$isDupe = 'Duplicate Added ' . $checkCount . ' to slug...<BR>';
$newSlug = $newVal . $checkCount;
$checkCount ++;
}
if($updateVal != $newVal){
$updateVal = $newSlug;
}
I am obviously doing something wrong, I need the while loop on the next iteration to use the newSlug value set in the loop, from my various attempts i am not at all sure if this is possible.
Whats the best way to accomplish this?
$newVal is not ever given a value, but it is used twice (second block of code). I think you need something like:
$newSlug = slugify($row_rs_locations['name_loc']);
$newVal = $newSlug;
i need the while loop on the next iteration to use the newSlug value
set in the loop
In the while loop you do
$newSlug = $newVal . $checkCount;
But $newVal does not exist. Replace that line with the following:
$newSlug .= $checkCount;

Categories