using limit in get function - codeigniter - php

I'm using codeigniter.
Now,I would like to use limit/offset statement.
My query :
$data['all'] = $this->m_general->get('pm', array(
'user_sender' => 1,
'admin_delete' => 0
) , false);
For example :
I want using limit 0,100

You can use like below.
Replace your values with limit and offset
$data['all'] = $this->m_general->get('pm', array(
'user_sender' => 1,
'admin_delete' => 0
) , limit,offset);

Related

How to LIMIT a Query which is already been selected?

I am trying to LIMIT a Query which is already been selected. I know I can directly do it in my query select, but due to some logics of the code, if I do that way I have to run the query selection twice which (I believe) will increase the computational time!
So, what I am trying is this:
$query1 = $mysqli->query("SELECT * FROM tableName WHERE someconditions");
then, I need to re-select a sub-selection of the $query1 for my Pagination. What I am trying to do is something like this;
$query2 = LIMIT($query1, $limit_bigin, $limit_end);
where $limit_bigin, $limit_end provide the LIMITING range (start and end respectively).
Could someone please let me know how I could do this?
P.S. I know I can do it directly by:
$query1 = $mysqli->query("SELECT * FROM tableName WHERE someconditions");
$query2 = $mysqli->query("SELECT * FROM tableName WHERE someConditions LIMIT $limit_bigin, $limit_end");
But this is running the query twice and slows down the process (I must run the first query without limits due to some logics of the program)
EDIT 1
As per the answers I tried using array_slice in PHP. BUT, since Query is an object it doesn't give the results that was expected. A NULL is resulted form
array_slice($query1, $start, $length, FALSE)
If you have already carried out the query and the result set has been returned to your PHP, you can not then LIMIT it. As you state, then running a second SQL execution of a subpart of the same query is wasteful and repetative.
Don't
Repeat
Yourself.
DRY.
As I said above, repetition causes issues with maintainability as you can easily forget about repetition, tweaking one SQL and forgetting to tweak the other.
Don't
Repeat
Yourself.
DRY.
Use PHP instead
Once you have executed the query, the result set is then passed back to PHP.
So assuming you have a $var with the contents of you SQL query, then you simply need to select the valid rows from the $var, not from the database [again].
You can do this using PHP numerous Array functions. Particularly array_slice().
So;
$query1 = $mysqli->query("SELECT * FROM tableName WHERE someconditions");
Now, to select the second page, say for example rows 10 to 20:
$query2 = array_slice($query1, (10-1), 10 );
This wil then "slice" the part of the array you want. Remember that the array counts will start at zero so to grab row 10 (of an index starting at 1, Typical of a MySQL Auto Increment Primary Key), then you will need to select X number of rows from row (10-1) .
Please also read the manual for PHP array_slice().
Further
As referenced in comments, there is no guarentee that your SQL will return the same values each time in the same order, so it is highly recommended to order your results:
$query1 = $mysqli->query("SELECT * FROM tableName
WHERE someconditions ORDER BY primary_key_column");
Example Data:
$query1 = $mysqli->query("SELECT * FROM tableName WHERE someconditions ORDER BY id");
/***
$query1 = array {
0 => array { 'id' => 1, 'user' => "Jim", 'colour' => "Blue" },
1 => array { 'id' => 2, 'user' => "Bob", 'colour' => "Green" },
2 => array { 'id' => 3, 'user' => "Tom", 'colour' => "Orange" },
3 => array { 'id' => 4, 'user' => "Tim", 'colour' => "Yellow" },
4 => array { 'id' => 5, 'user' => "Lee", 'colour' => "Red" },
5 => array { 'id' => 6, 'user' => "Amy", 'colour' => "Black" }
}
***/
$page = 2;
$size = 3; // number per page.
$start = ($page - 1) * $size; //page number x number per page.
// Select the second page of 3 results.
$query2 = array_slice($query1, $start, $size , FALSE);
/***
$query2 = array {
0 => array { 'id' => 4, 'user' => "Tim", 'colour' => "Yellow" },
1 => array { 'id' => 5, 'user' => "Lee", 'colour' => "Red" },
2 => array { 'id' => 6, 'user' => "Amy", 'colour' => "Black" }
}
***/
You can then use these in a foreach or other standard array manipulation technique.

cakephp group by with n result for each group

I need to extract 3 result from each category in a database using cakephp, I tried to query in database using mysql session variable and conditions as below
SELECT *, #question_cat_rank := 0, #question_cat_country:=''
FROM
(SELECT *,
#question_cat_rank := IF(#question_cat_country = question_setname.question_cat, #question_cat_rank + 1, 1) AS question_cat_rank,
#question_cat_country := question_cat
FROM question_setname
ORDER BY question_cat desc
) ranked
WHERE question_cat_rank <= 3
its working fine in mysql query analyzer but when i query using cakephp its returning all results in table instaed of 3 results
i tried to create it using cakephp way like below
public $virtualFields = array(
'#catvirt' => 1,
'#catvirt2' => 'question_cat',
'incrmt' => 'IF(#catvirt2 = question_cat, #catvirt+1, 1)',
);
function getquestionGroup(){
$result1 = $this->find('all', array(
'fields' => array('question_cat', '#catvirt2', 'incrmt'),
'#catvirt2'=> 'question_cat',
'#catvirt' => '#catvirt'
)
);
$result = $this->find('all', array($result1,
'conditions' => array('#catvirt <=' => 3),
)
);
i tried to execute as prepared statementand stored procedure also still no luck its returning all results
any help will be appreciated
I would write that query this way:
SELECT x.*
FROM
( SELECT *
, #question_cat_rank := IF(#question_cat_country = question_cat, #question_cat_rank + 1, 1) question_cat_rank
, #question_cat_country := question_cat
FROM question_setname
, (SELECT #question_cat_rank := 0, #question_cat_country:='') vars
ORDER
BY question_cat DESC
) x
WHERE question_cat_rank <= 3;

CakePHP order not working

Hi i am using CakePHP version - 2.5.5.
I have a table name chat_ategory_mages I want to get Average number of Frequency Order by Descending. Know about the Frequency please check - How to get Average hits between current date to posted date in MySQL?
chat_ategory_mages
id chat_category_id hits created
------------------------------------------------
1 5 10 2014-11-07 11:07:57
2 5 8 2014-11-10 05:10:20
3 5 70 2014-10-04 08:04:22
Code
$order=array('Frequency' => 'DESC');
$fields=array(
'ChatCategoryImage.id',
'ChatCategoryImage.chat_category_id',
'ChatCategoryImage.created',
'ChatCategoryImage.hits',
'hits/(DATEDIFF(NOW(),created)) AS Frequency',
);
QUERY-1
$rndQry=$this->ChatCategoryImage->find('all',array('conditions'=>array('ChatCategoryImage.chat_category_id'=>$cetegory_id), 'fields'=>$fields, 'order'=>$order, 'limit'=>10));
pr($rndQry); //WORKING FINE
QUERY-2
//THIS IS NOT WORKING
$this->Paginator->settings = array(
'conditions'=>array('ChatCategoryImage.chat_category_id'=>$cetegory_id),
'fields'=>$fields,
'limit' => 10,
'order' => $order,
);
$getCategoryImages = $this->Paginator->paginate('ChatCategoryImage');
pr($getCategoryImages); //NOT WORKING
Above table if i write simple cakephp query the order is working fine but when i am using cakephp pagination it is not working. If i am using $order=array('hits' => 'DESC'); this its woring perfect. Showing result 70,10,8 consistently but when i am adding Frequency it the result not coming the descending order.
Mysql Query
QUERY-1 :
SELECT ChatCategoryImage.id, ChatCategoryImage.chat_category_id, ChatCategoryImage.hits, ChatCategoryImage.created, hits/(DATEDIFF(NOW(),created)) AS Frequency, FROM myshowcam.chat_category_images AS ChatCategoryImage WHERE ChatCategoryImage.chat_category_id = 5 ORDER BY Frequency DESC LIMIT 10
QUERY-2 :
SELECT ChatCategoryImage.id, ChatCategoryImage.chat_category_id, ChatCategoryImage.hits, ChatCategoryImage.created, hits/(DATEDIFF(NOW(),created)) AS Frequency, FROM myshowcam.chat_category_images AS ChatCategoryImage WHERE ChatCategoryImage.chat_category_id = 5 LIMIT 10
What is the problem and why its not coming ORDER BY Frequency in the second query?
Thanks
chinu
You can use virtualFields
$this->ChatCategoryImage->virtualFields = array('Frequency' => 'hits/(DATEDIFF(NOW(),created))');
changing the way of order
$order = array('Frequency' => 'desc');
This happened to me to. You have to add to the paginate function the third parameter $whitelist. For example.
$this->Paginator->settings = array(
'conditions'=>array('ChatCategoryImage.chat_category_id'=>$cetegory_id),
'fields'=>$fields,
'limit' => 10,
'order' => $order,
);
$scope = array();
$whitelist = array('ChatCategoryImage.id', ...); //The fields you want to allow ordering.
$getCategoryImages = $this->Paginator->paginate('ChatCategoryImage', $scope, $whitelist);
pr($getCategoryImages);
I do not know why this is happening. I tried to see the code inside the paginate function but i could not figure it out.
Your code was lil wrong
$this->paginate = array(
'conditions' => array('ChatCategoryImage.chat_category_id'=>$cetegory_id),
'limit' => 10, 'order' => 'Frequency' => 'DESC');
$getAllCourses = $this->paginate('ChatCategoryImage');

How to use where and group by conditions with cakephp2?

I'm new to cakephp2 and I wanted to ask you a little favor.I'm currently learning cakephp2 but I'm having some hard time trying to understand how to use where and groupby clause in cakephp2.
I am tring to convert this sql query below to cakphp2 but how will I do it using find() ?
select params,count(params) from pv_logs
where dt = '2014/9/25' and is_crawler = 0
group by params order by count(params) desc limit 100 ;
This is how I did it in cakephp2 format but do you see something wrong with this ?
$pvcount = $this->PvLog->find('all', array(
'fields' => array('dt','params','count(params)'),
'conditions'=>array('PvLog.dt'=>'2014/9/25','PvLog.is_crawler'=>0),
'group'=>array('PvLog.params'),
'order'=>array('PvLog.count(params)'),
'limit' => 100,
));
Try Below
$this->PvLog->virtualFields['params_count']='count(params)';
$pvcount = $this->PvLog->find('all', array(
'fields' => array('dt','params','params_count'),
'conditions'=>array('PvLog.dt'=>'2014-09-25','PvLog.is_crawler'=>0),
'group'=>array('PvLog.params'),
'order'=>array('params_count'=>'asc'),
'limit' => 100,
));

Is it possible to specify two limit values(from, offset) in one Phalcon\Mvc\Model::find() method?

For a moment i found following example:
$robots = Robots::find(array("limit" => 100));
Is it possible to define two values for limit, "from" and "offset"?
In Zend Framework it was possible with Db adapter function, that looked like this:
$db->select()->limit($from, $offset)
Try this:
$collection = Model::find(array(
"limit" => array('number' => $from, 'offset' => $offset)
));
You could always use PHQL which supports the OFFSET like so (in a controller):
$sql = 'SELECT * FROM Robots LIMIT 100 OFFSET 10';
$stmt = $this->modelsManager->createQuery($sql)
$results = $stmt->execute();
limit parameter can not only accept int values.
this example would work too:
$offset = 20;
$from = 10;
$collection = Model::find(array("limit" => $from . ',' . $offset));
You can just pass another element called offset and specify the value in it,refer to the given below example:
$orders=Orders::find(array(
"order" => "id DESC",
"limit" => 10,
"offset" => 0
));
You may refer to following link for detailed information:
https://docs.phalconphp.com/en/latest/reference/models.html
You can make your query pretty customizable doing this:
<?php
$notifications = \UserNotification::find([
"user_id = :user_id: ORDER BY date DESC LIMIT 5",
"bind" => [
"user_id" => 1
]
]);

Categories