获取分页,MYSQL,ONE QUERY中的总行数

时间:2014-08-11 00:20:29

标签: php mysql pagination

我有一个基于给定参数构建MYSQL查询的函数。它看起来像这样:(不要担心理解它,只是给它一个快速的看法)

 public function getAll($params = array()) {   
    $whereused = false;

    /*
     * -- BASE QUERY
     */
    $query = "SELECT ".$this->tablename.".*, itemtypes.title AS itemtypename";
    if(!empty($params["hasCategory"]) && $params["hasCategory"] == true) {
        $hasCat = true;
        $query .= ", ".$this->categoriestable." AS categoryname";
    }
    $query .=" FROM ".$this->tablename." LEFT JOIN itemtypes ON ".$this->tablename.".itemtype = itemtypes.id";
    if(!empty($hasCat)) {
        $query .= " LEFT JOIN ".$this->categoriestable." ON ".$this->tablename.".category = ".$this->categoriestable.".id";
    }
    //echo $query; exit; //DEBUG

    /*
     *  -- CONDITIONS
     */

    //SEARCH ALGORITHM
    if(!empty($params["search"])) {
        $query .= " WHERE
                    ".$this->tablename.".title LIKE :search OR
                    ".$this->tablename.".content LIKE :search";
        if($params["searchByCat"] == true && $hasCat === true) {
            $query .= " OR ".$this->tablename.".category = :search";
        }
        $whereused = true;
    }

    //Returning inactive or active items
    if(!empty($params["activeonly"])) {
        if(!$whereused) {
            $query .= " WHERE active = 1"; 
        } else if($whereused) {
            $query .= " AND active = 1"; 
        }
    } else if(!empty($params["inactiveonly"])) {
        if(!$whereused) {
            $query .= " WHERE active = 0"; 
        } else if($whereused) {
            $query .= " AND active = 0"; 
        }
    } // ELSE Return both anyway
    // ........ MORE CODE GOES ON
}

如您所见,查询构建为函数,知道参数已正确设置。 当我分页时,我所做的是:

//For pagination
    if(!empty($params["limit"]) && !empty($params["set"])) {
        $set = ($params["set"] - 1) * $params["limit"];
        $query .= " LIMIT ".$params["limit"].", ".$set;
    }

在功能结束时,它工作正常。但是当我想获得此查询返回的行数时,如果设置了参数,我必须运行它两次:

- 一个返回实际的RESULT SET - 另一个只获得总行数,将1作为$ params [" set"]并将999999999作为$ params [" limit"];

因此,每次用户更改页面时,都必须执行两个查询,有没有办法在不运行查询两次的情况下始终返回总行数?

希望我能解释清楚。

0 个答案:

没有答案