February 3rd, 2013, 07:39 AM
How to get the last and first results from a MYSQL query using PHP PDO?
I have a simple articles table with IDs. I want to get the highest and lowest ids from the latest 10 results using PHP PDO prepared statements. For example, if there are 11 ids, the result should be 2 and 11 and if there are 4 ids, should be 4 and 1 and so on.
The above will always return 11 if there are 11 records and 10 if there are 10 records. So, the query ignores the PDO::FETCH_ORI_LAST and PDO::FETCH_ORI_FIRST part of the query.
$aid = $DBH->prepare("SELECT id FROM articles ORDER BY id DESC LIMIT 10");
$row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
$lowest_article_id = $row;
$row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_FIRST);
$highest_article_id = $row;
Thanks in advance
February 3rd, 2013, 02:24 PM
Those options require a scrollable cursor.
February 4th, 2013, 06:38 AM
Tried adding the scrollable cursor to the prepare statement but it's still not working. Someone on another forum pointed me to a bug from 2005 about this issue.
This bug is still not fixed yet!