duanboshe0001 2010-02-11 10:43
浏览 42
已采纳

使用PHP修改SQL SELECT语句

How best to alter a SQL SELECT statment's field list to a COUNT(*) using PHP?

e.g

SELECT blah, blah, blah FROM tbl_blah WHERE blah;

to

SELECT COUNT(*) FROM tbl_blah WHERE blah

I have considered mysql_num_rows... but I am pretty sure it would be more efficient to edit the statement. I am guessing it could be solved with a regex expression... :S

  • 写回答

2条回答 默认 最新

  • doukoumi3389 2010-02-11 10:48
    关注

    You can do this using preg_replace():

    <?php
    $sql = "SELECT blah, blah, blah FROM tbl_blah WHERE blah;";
    
    $newSql = preg_replace(
        "/^SELECT (.*) FROM (.*)$/",
        "SELECT COUNT(*) FROM $2",
        $sql);
    
    echo $newSql;
    // SELECT COUNT(*) FROM tbl_blah WHERE blah;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部