CodeIgniter problem with limit - php

I have a LoteModel:
public function selecionar($where = NULL, $limit = NULL, $order_by = NULL) {
if(!is_null($where)) {
$this->db->where($where);
}
if(!is_null($limit)) {
$this->db->limit($limit);
}
if(!is_null($order_by)) {
$this->db->order_by($order_by);
}
return $this->db->get(_LOTE_);//_LOTE_ is a constant for my table name
}
and I call it like this:
$config['per_page'] = '5';
$limite = $config['per_page'].','.$this->uri->segment(3); //the segment is ok, I receive it
$lotes = $this->LoteModel->selecionar(array('quadra_id'=>$quadra_id, 'lote_status'=>1), $limite, 'lote_endereco');
I have checked the SQL result for that query:
SELECT * FROM (`realestate_lote`) WHERE `quadra_id` = '1' AND `lote_status` = 1 ORDER BY `lote_endereco`
The thing is, it’s not generating my LIMIT, it will only work if I add it to the LoteModel method.
I’m working with pagination.
Thanks in advance for any help =)

You can't pass a string like "5,1" to CI's ActiveRecord limit function.
The function requires two parameters.
Split the limit string by "," and pass the two values like the example below.
$limit = explode(',', $limit);
$this->db->limit($limit[0], $limit[1]);
Hope this helps...

Related

easyUI datagrid pagination displaying Nan of nan items

Im doing an application with code igniter and easyui datagrid, I set
pagination:true
but the next and back button aren't working and the pagination info says
Displaying 1 to NaN of NaN items
I've been googling around but still no luck.
here is my JS:
var tablegrid = $('#datagrid');
var cols = [[
{field:'referal',title:'Referal',align:'center'},
{field:'firstName',title:'First Name',align:'center'},
....
]];
tablegrid.datagrid({
title: "Register a Friend",
url: base_url + 'notification/get_friend_notification',
columns: cols,
pagination: true,
rownumbers: true,
singleSelect: true
});
and here is my controller
$results["rows"] = $this->mnotification->get_friend_list();
echo json_encode($results);
The model:
public function get_friend_list() {
$params = $this->input->post();
$offset = $params['rows'] * $params['page'];
$sql = $this->db->query(/* sql query.. */);
return $sql->result();
}
Thanks to my trusty colleague he helped me find for an answer. What I did was
I retained the js as it is.
modified my controller a bit, instead of
$results["rows"] = $this->mnotification->get_friend_list();
I modified it into a variable that accepts an array from the model:
$results = $this->mnotification->get_friend_list();
the mnotification model (very important), this is where I passed the result as an array
public function get_friend_list() {
$result = array();
$params = $this->input->post();
$offset = $params['rows'] *( $params['page'] - 1);
$query = "SELECT * FROM ..."; // sql statement
// created index total for the total number of fetched data.
$result['total'] = $this->db->query($query)->num_rows;
//appended limit and offset on the query string.
$query .= " LIMIT {$params['rows']} OFFSET {$offset}";
// pass all the result in index total.
$result['rows'] = $this->db->query($query)->result();
}
I hope it helps!

Wrong data updated in mysql when function runs first time

function renew_status($propertyId){
$code = '';
$code = mt_rand(500000, 999999);
$q = "UPDATE `ps_listings` SET
`accessCode` = $code,
`renew` = '0'
WHERE `id` = $propertyId ";
mysql_query($q) or die(mysql_error());
$this->db->select('accessCode')->from('ps_listings');
$this->db->where(array('id' => $propertyId));
$query = $this->db->get();
$results = $query->result();
return $results[0]->accessCode;
}
I am updating a mysql table through codeigniter function. first time when i access my function it updates wrong number but if i refresh the page correct value is updated.
return $results[0]->accessCode; gives me this code 893195. while in database it saves 997228. Please Help me
Try this
function renew_status($propertyId){
$code = '';
$code = mt_rand(500000, 999999);
$data = array('accessCode' => $code, 'renew' => '0');
$this->db->where('id',$propertyId);
$this->db->update('ps_listings',$data);
$this->db->select('accessCode');
$this->db->where('id',$propertyId);
$query = $this->db->get('ps_listings');
$results = $query->result_array();
return $results[0]->accessCode;
}
1) Use mysql_affected_rows for check works update or no.
2) I think refresh page is wrong way. Use Session for deny double update.
3) For debugging retrieve and print accessCode before updating, after, and in
result(UI).
1) is "id" column unique and not null?
2) what does the following code returns :
echo count($results);

Codeigniter limit for pagination

I made this function in codeigniter:
public function get_users_pagination($q, $perpage, $pagenr, $type = 1)
{
$query = $this->db->get_where('korisnici_tbl', array("type" => $type), $perpage,$pagenr);
$this->db->like('email', $q);
$this->db->or_like('name', $q);
return $query->result();
}
But when the result is less than the $perpage variable it still returns rows in the amount of $perpage.
So if the $pagenr is for example 10 and there are 2 rows with type 1 it just returns 8 other rows of type 2 with it.
You can group the ORs like this
$like = '(email LIKE \'%'.$q.'%\'';
$like .= ' OR name LIKE \'%'.$q.'%\')';
$this->db->where($like);
You can try like this way :
$query = $this->db->get_where('korisnici_tbl', array("type" => $type));
$this->db->like('email', $q);
$this->db->or_like('name', $q);
$this->db->limit($pagination_start, $pagination_length);
Just put on your model function:
$limit = 3; //maximum row's which you want to show in page's:

How to count how many queries on page load?

I used this simple following function for my SQL select query:-
I want to be able to count how many queries is being executed when running this function? If this function has been called 10 times then it will be calling SQL query 10 times. How can I output this as string? I tried using
count($sql);
but this produces..
1111111
Which means 7 times, when I try use
array_sum()
it doesn't add all the ones..
any help with this please?
many thanks
public function select($rows = '*', $table, $where = null, $order = null, $limit = null, $echo = null) {
$sql = "SELECT ".$rows." FROM {".$table."}";
if($where != null) {
$sql .= " WHERE ".$where;
}
if($order != null) {
$sql .= " ORDER BY ".$order;
}
if($limit != null) {
$sql .= " LIMIT ".$limit;
}
if($echo != null) {
echo $sql . '<br />';
}
//echo $sql . '<br />';
echo count($sql);
return $sql;
}
The simplest approach would be to wrap your SQL queries into class/function and plant accounting there. Then you just need to init your counter as very first thing in your script. Increase counter on each query. Display counter at the end of your scripts.
But in your case, if your return string "1111" means 4 queries (like each character means single query), then just do ordinary strlen() on that string and you are done.
you can use static variable inside your function and increase it each time.
You could work with a static variable that can be accessed within and outside the function.
public function select (...) {
static $count_sql;
[your function code]
$count_sql++;
}

Return value in foreach loop in CodeIgniter

I am having some trouble in returning values from model to controller Using CodeIgniter. I am passing two arrays from controller to model. I am checking whether both the arrays are not empty and looping them using foreach loop to fetch some values from database and returning the query to controller. Here's my current code
if (!empty($search_for_area) && !empty($search_for_requirement))
{ foreach($search_for_requirement as $search_value_1)
{
foreach($search_for_area as $search_value_2)
{
if($search_value_2 != null && $search_value_1 != null)
{
$nearbytution = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name');
print_r($nearbytution->result());
}
}
}
//Line 1
}
print_r($nearbytution->result()); works fine and i am able to view the results. Where should i put return $nearbytution; so that i can get all the fetched values? I tried it in Line 1 but i was getting only values of last array value.
function returnStuff($search_for_area,$search_for_requirement) {
$arr_area = array();
$arr_filter = array();
if ( ! empty($search_for_area) and ! empty($search_for_requirement)) {
foreach($search_for_requirement as $search_value_1) {
foreach($search_for_area as $search_value_2) {
if($search_value_2 != null && $search_value_1 != null) {
$arr_area[] = $this->db->escape($search_value_2);
$arr_filter[] = $this->db->escape_like_str($search_value_1);
}
}
}
}
$str_area = 'NULL';
if ($arr_area)
$str_area = implode(', ', $arr_area);
$str_filter = "'^-$'";
if ($arr_filter)
$str_filter = "'(".implode('|', $arr_filter).")'";
$query = $this->db->query("
SELECT name, area, contactno
FROM tut_listing
WHERE area IN ({$str_area}) AND categoryfilter REGEXP {$str_filter} and partner > '' group by name
");
return $query->result();
}
Seriously, do consider this approach. You only need to bother the poor Mysql server with one call and you get all the data you want at the same time.
Apart from that, practice consistent style in your code. It will save both your time and your hair in the long run.
CodeIgniter escape()
MySQL REGEXP
Try this in the loop:
$nearbytution[] = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name')->result();
return $nearbytution;may then be placed at your "Line 1". It will contain an array of query results.
Unless I misunderstand your question why don't you just store all the results in a big array and then return that array?
function returnStuff($search_for_area,$search_for_requirement) {
$data = array();
if (!empty($search_for_area) && !empty($search_for_requirement)) {
foreach($search_for_requirement as $search_value_1) {
foreach($search_for_area as $search_value_2) {
if($search_value_2 != null && $search_value_1 != null) {
$nearbytution = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name');
$data[] =$nearbytution->result());
}
}
}
}
return $data;
}
Now $data will be an array of results, each containing the query results. If your result set has to be cleaned up (to remove duplicates for instance) you can just loop through it and do that cleanup.
What you could also maybe do is build a large SQL query in your foreach loops and then just do that one big query and return the results.

Categories