donv29560 2011-08-09 16:11
浏览 53
已采纳

使用PDO修改预准备语句的查询字符串

I'm extending the PDO class to add functions that manipulate the querystring of a prepared statement. For example make a query searchable or add pagination.

For example:

$documents_query = $DB->prepare( "SELECT id, title, file_name, datetime_added
                                    FROM documents
                                    ORDER BY datetime_added DESC" );

$documents_query->paginate( $page_number, RESULTS_PER_PAGE );

The question is how to modify the querystring (which is readonly) and save it, so it can get executed later on?

This is an example of how my extended PDOStatement class looks like:

class CustomStatement extends PDOStatement
{
    public function paginate( $current_page, $max_results )
    {
        // Add SQL_CALC_FOUND_ROWS so we can count the total amount of results
        $select_index = stripos( $this->queryString, 'SELECT' );

        $statement = substr_replace( $this->queryString, 'SELECT SQL_CALC_FOUND_ROWS', $select_index, 6 );

        // Add LIMIT to the end of the query
        $start_limit = ( $current_page - 1 ) * $max_results;

        $statement = $statement . ' LIMIT ' . $start_limit . ', ' . $max_results;

        // What to do here?
        return $this->prepare( $statement );
    }
}
  • 写回答

2条回答 默认 最新

  • douzhi9921 2011-08-09 17:55
    关注

    You know, I generally find that extending PDOStatement is not your best option. At a minimum, subclassing PDOStatement means you need to subclass PDO. It gets messy. There also isn't really terribly much benefit in doing that -- you can't modify the original query, PDOStatement can't really be modified.

    It is better, in my experience to write a wrapper around PDO which will allow you to manipulate the contents. This will let you manipulate the strings before they get to the point where you want to paginate. This also happens to be the way that most frameworks will use PDO.

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

报告相同问题?

悬赏问题

  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测