3

Is there a way to limit the CSqlDataProvider? When i force the totalItemCount to 3 for example the result is not taken into consideration.

$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM tbl_user')->queryScalar();
$sql='SELECT * FROM tbl_user';
$dataProvider=new CSqlDataProvider($sql, array(
  'totalItemCount'=>3,    
  'pagination'=>array(
    'pageSize'=>10,
   ),
));

When i try to limit the query LIMIT 3 and comment totalItemCount line, i receive:

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: ... LIMIT 3 LIMIT 10

It appears that whatever i do the sql is appended with LIMIT 10.

2
  • Did you already solve it?
    – felipe.zkn
    May 9, 2014 at 17:33
  • Yes, try my answer or set pagination to false then set limit. May 11, 2014 at 6:21

2 Answers 2

2

While you are using CSqlDataProvider, You can limit your total items in your sql. As Yii's official document wrote:

Like other data providers, CSqlDataProvider also supports sorting and pagination. It does so by modifying the given sql statement with "ORDER BY" and "LIMIT" clauses. You may configure the sort and pagination properties to customize sorting and pagination behaviors.

CSqlDataProvider

So you can easily do it by changing your sql like below:

$sql='SELECT * FROM tbl_user LIMIT 3';
5
  • Your solution gives: CDbCommand failed to execu tehe SQL statement: SQLSTATE[42000]: Syntax error or access violation: ... LIMIT 3 LIMIT 10 Feb 5, 2014 at 20:51
  • You have syntax error, check your sql.As it says You have two limit in your sql. Or remove 'totalItemCount'=>3 Feb 5, 2014 at 20:53
  • If i remove the Limit 3 the query runs but returns 10 results. Yes i removed 'totalItemCount' line. Feb 5, 2014 at 20:57
  • Did you remove 'totalItemCount'=>3 ? Feb 5, 2014 at 20:59
  • 1
    You need to set pagination to false to disable it. Then set limit as in this answer.
    – topher
    Feb 5, 2014 at 21:46
1

The solution is to add ; at the end of the sql statement, in this way the cpagination is not adding the default LIMIT 10 clause.

 $sql = 'SELECT * FROM tbl_user LIMIT 3;';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.