doudou5101 2013-02-03 13:21
浏览 171
已采纳

如何使用PHP PDO从MYSQL查询中获取最后的结果?

I have a simple articles table with IDs. I want to get the highest and lowest ids from the latest 10 results. 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. I use PHP PDO statements.

$aid = $DBH->prepare("SELECT id FROM articles ORDER BY id DESC LIMIT 10"); 
$aid->execute(); 
$row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
$lowest_article_id = $row[0];
$row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_FIRST);
$highest_article_id = $row[0];

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 part of the query.

Thanks

  • 写回答

3条回答 默认 最新

  • duangu9173 2013-02-03 16:30
    关注

    I did some checking and from the docs it sounds like this should work. You need to enable cursor scrolling when you prepare the sql.

    $aid = $DBH->prepare("SELECT id FROM articles ORDER BY id DESC LIMIT 10", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); 
    $aid->execute(); 
    $row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
    $lowest_article_id = $row[0];
    $row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_FIRST);
    $highest_article_id = $row[0];
    

    That being said it does not for me :/

    I did more reading/testing and I found these two bug reports:
    https://bugs.php.net/bug.php?id=34625 (this one is from 2005 though and I am almost positive there is cursor functionality in MySQL these days).
    https://bugs.php.net/bug.php?id=57623

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号