This question already has an answer here:
I'm using PDO in my application. But I have a problem while I'm working with prepared statements in a query that contains LIMIT
. What's the problem?
Codes:
$start = 0;
$rows = 20;
$sql = "SELECT * FROM tbl_news ORDER BY date DESC LIMIT ?, ?";
$q = $db->prepare($sql);
$q->execute(array($start , $rows));
Error:
check the manual that corresponds to your MySQL server version for the right syntax to use near ''0', '20''
date
is a reserved word you have to wrap it withback-ticks
I just stumbled upon the same problem. For me, using my own statement class (extending
PDOStatement
) with my ownexecute()
method fixed it.This is the class:
To tell PDO to use this statement class instead of the default one, do this:
Now the code in the question will work:
The only thing you have to make shure is that the variables bound to the statement have the correct type, integer. If you have a numeric string, e.g. from the
$_GET
array, you can do something like this:I'm not shure if there is an easier way for the last thing, but at least it works fine for me.
Regarding to post LIMIT keyword on MySQL with prepared statement , the code below could solve my problem.
Thanks Álvaro G. Vicario and Maerlyn
You can do like this:
It is a known bug which was fixed in 5.5.6 from memory.
From the article: LIMIT doesn't allow variables in any context. Its arguments must be integer constants.
Further Edit: (There is contention on the matter) User variables are accepted arguments of LIMIT clause in prepared statements, and SQL syntax for prepared statements can be used in stored procedures.
Third Edit: This link explains that these should work with prepared statements.