Preg_replace()删除除查询结尾之外的所有内容

时间:2014-07-02 18:08:55

标签: php mysql regex pagination

在一切之前,抱歉我的英语不好。

我有这个问题:

SELECT t1.*,(SELECT COUNT(*) FROM table_a t2 WHERE t1.id=t2.id_c AND t2.status=1) AS aula 
FROM table_c t1 
WHERE t1.status=1 
AND t1.id IN (SELECT t3.id_c FROM table_cu t3 WHERE t3.id_c=t1.id AND t3.id_u=1) 
AND t1.id IN (SELECT t4.id_c FROM table_cp t4 WHERE t4.id_c=t1.id AND t4.id_p=3) 
LIMIT 0,25

这个查询返回给我一组结果,直到现在都没有问题,但我有一个非常基本的进程的分页类:它计算我得到了多少条目,然后它将条目分成几部分,然后用这个值我分页。

问题出在这个方法的分页类中,这里的代码是:

function total_entries()
{

    $db = new db(DB_USER, DB_PASS, DB_NAME, DB_HOST);

    $qtdEntries = 0;

    $queryQtd = $this->sql;
    $queryQtd = preg_replace("/SELECT (.*) FROM /sei", "'SELECT COUNT(*) as qtd FROM '", $queryQtd);
    $queryQtd = preg_replace("/ORDER BY (.+)/", "", $queryQtd);
    $queryQtd = preg_replace("/LIMIT (.+)/", "", $queryQtd);

    $resultAll = $db->get_row($queryQtd); //Gets the result, in this case, it returns the number of entries

    if($resultAll){
        $qtdEntries = $resultAll->entries; //Number of entries
    }

    return $qtdEntries;
}

基本上当我运行这个方法时,它内部的查询返回如下:

SELECT COUNT(*) as qtd FROM table_cp t4 WHERE t4.id_c=t1.id AND t4.id_p=3)

什么时候应该返回这样的东西:

SELECT COUNT(*) as qtd FROM table_c t1 WHERE t1.status=1

有任何想法如何纠正这个问题?

1 个答案:

答案 0 :(得分:2)

解决此问题的更好方法是使用MySQL内置功能:

您只需在SELECT关键字与SQL_CALC_FOUND_ROWS函数结合后添加FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS t1.*,(SELECT COUNT(*) FROM table_a t2 WHERE t1.id=t2.id_c AND t2.status=1) AS aula 
FROM table_c t1 
WHERE t1.status=1 
AND t1.id IN (SELECT t3.id_c FROM table_cu t3 WHERE t3.id_c=t1.id AND t3.id_u=1) 
AND t1.id IN (SELECT t4.id_c FROM table_cp t4 WHERE t4.id_c=t1.id AND t4.id_p=3) 
LIMIT 0,25

如果没有LIMIT子句,要获取行数,现在可以使用语句

SELECT FOUND_ROWS();

作为下一个查询。

正则表达式方法的问题是使正则表达式正确。匹配通常是贪婪的,它会尽可能地匹配。在这种情况下,它将恰好匹配WHERE子句的最后一个条件,因为此条件使用带有FROM关键字的子选择。因为那个模式

SELECT (.*) FROM

$queryQtd = preg_replace("/SELECT (.*) FROM /sei", "'SELECT COUNT(*) as qtd FROM '", $queryQtd);

比SELECT的字段列表(包含带FROM的子选项)的匹配要多得多。