views:

95

answers:

4

I have a query

public static function TestQuery(

 $start=0,
 $limit=0){


 $sql = "
SELECT     count(*) AS total
FROM    db.table1
JOIN    db.table2
 ON     table1.fieldID = {$fieldID}

AND    table2.assigned = 'N'";



  $qry = new SQLQuery;
  $qry->query($sql);
  if($row = $qry->fetchRow()){
   $total = intval($row->total);
  }

 return $total;

} 

which works fine but when I add the limit as below, then it doesnt work and gives me errors

public static function TestQuery(

 $start=0,
 $limit=0){


 $sql = "
SELECT     count(*) AS total
FROM    db.table1
JOIN    db.table2
 ON     table1.fieldID = {$fieldID}

AND    table2.assigned = 'N'";

//this fails   
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";  
//  
  $qry = new SQLQuery;
  $qry->query($sql);
  if($row = $qry->fetchRow()){
   $total = intval($row->total);
  }

 return $total;

} 

Any help will be appreciated

+4  A: 

Put a space in front of LIMIT:

" LIMIT {$startRecord}, {$recordLimit} "

without the space you sql will result in a syntax error.

Edit: This is answer is not correct! MySQL will not error without a space before LIMIT (however, earlier versions of phpmyadmin will incorrectly parse such sql).

webbiedave
Why will there be an error without the space?
Mark Byers
Mysql errors on WHERE field = 'N'LIMIT ...
webbiedave
@webbiedave: Not for me. What version of MySQL are you using?
Mark Byers
intersesting. I'm using 5.0.27-community.
webbiedave
I then tried it on 5.0.51a and it does not error!
webbiedave
@webbiedave: Also no error on 5.1.41-community... strange.
Mark Byers
@Mark Byers: Whoops. Guess what? Error is being caused by earlier versions of phpmyadmin and not mysql!
webbiedave
@webbiedave: Never mind. Error or no error, I still think having the space there is much better style.
Mark Byers
@Mark Byers: agreed.
webbiedave
+2  A: 

Try changing

if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";

To

if($recordlimit > 0) $sql .= " LIMIT {$start}, {$limit} ";

It looks like your SQL is getting squished together and should be getting a bad syntax error, and you had the wrong (seemingly) variable names in there.

manyxcxi
+3  A: 

Your variables are called $limit and $start:

if($limit > 0) $sql .= " LIMIT {$start}, {$limit} "; 
Mark Byers
A: 

wrong variables if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} "; solved thanks

If Mark Byers answer is correct, you should accept it. Although I think my and manyxcxi changes are also necessary to get it working.
webbiedave
Please don't post follow-up comments to your question as answers. Also, if an answer provided your solution, please accept it.
Adam Robinson