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

时间:2011-08-09 16:11:01

标签: php pdo prepared-statement

我正在扩展PDO类以添加操作预准备语句的查询字符串的函数。例如,使查询可搜索或添加分页。

例如:

$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 );

问题是如何修改查询字符串(只读)并保存它,以便稍后执行?

这是我的扩展PDOStatement类的示例:

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 个答案:

答案 0 :(得分:3)

您知道,我通常发现扩展PDOStatement不是您的最佳选择。至少,子类化PDOStatement意味着您需要子类PDO。它变得凌乱。这样做也没有太大的好处 - 你无法修改原始查询,PDOStatement无法真正被修改。

根据我的经验,最好在PDO周围编写一个包装器,它允许你操作内容。这将允许您在之前操作字符串,使它们到达您想要分页的位置。这也恰好是大多数框架使用PDO的方式。

答案 1 :(得分:2)

准备好声明后,您无法对其进行修改。如果要在准备之前对其进行修改,请获取查询字符串,编辑所需内容,然后准备语句。