获取正确的行数和行数

时间:2016-07-28 20:44:49

标签: php mysql sql-server pdo

现在我已经使用PDO和SQL服务器轻松完成了这项工作,但我正在努力使其适用于任何常规查询。因为我希望我的MySQL表可以重复使用任何项目,所以我转向这里寻求帮助。

所以我将它用于PDO和SQL服务器的方式

function pagedQuery($dbh,$q,$sort,$offset,$limit,$params = array()) {
    $limit = preg_replace("/[^0-9]]/","",$limit);
    $offset = preg_replace("/[^0-9]]/","",$offset);
    $q = preg_replace("/^[^\w]*SELECT/i","SELECT COUNT(*) OVER() as num_rows, ROW_NUMBER() OVER(ORDER BY $sort) AS rownum,",$q);
    $q = "SELECT * FROM (".$q.") as pagingTable WHERE rownum > $offset AND rownum <= ($offset+$limit)";

    ## Prepare Query
    $stmt = $dbh->prepare($q);

    try {
        $stmt->execute($params);
    } catch(PDOException $e) {
        print $e->getMessage();
    }

    ## Return Results
    return $stmt->fetchAll();

现在很明显OVER功能不存在,而且必须修改MySQL。以下是我对新版本的尝试:

function mysqlPagedQuery($dbh,$q,$table,$sort,$offset,$limit,$params = array()) {
    $limit = preg_replace("/[^0-9]]/","",$limit);
    $offset = preg_replace("/[^0-9]]/","",$offset);
    $q = preg_replace("/^[^\w]*SELECT/i","SELECT (SELECT COUNT(*) as num_rows FROM ".$table.") AS num_rows, @rowN := @rowN + 1 AS rownum,",$q);
    $q = "SELECT * FROM (".$q.") as pagingTable WHERE rownum > $offset AND rownum <= ($offset+$limit)";

    ## Prepare Query
    $stmt = $dbh->prepare($q);

    try {
        $query = $dbh->query("set @rowN = 0;");
        $stmt->execute($params);
    } catch(PDOException $e) {
        print $e->getMessage();
    }

    ## Return Results
    return $stmt->fetchAll();

现在这将“工作”,因为你给它一个表但我很快意识到num_rows不会返回正确的值,除非给出了查询的所有WHERE子句。我将不得不以低效的方式解析它,我觉得有一个更简单的方法来做到这一点,而不是我正在实现它。

1 个答案:

答案 0 :(得分:0)

我最后感谢bobkingof12vs发布链接。不能直接给他答复,因为它没有在这里发布:(

function mysqlPagedQuery($dbh,$q,$sort,$offset,$limit,$params = array()){


$limit = preg_replace("/[^0-9]]/","",$limit);
$offset = preg_replace("/[^0-9]]/","",$offset);
//need to use the original query a few times to create paged 
$tempQuery = $q;
//replaces query's select with a count to get numrows
$q1 = "SELECT sql_calc_found_rows * FROM (".$tempQuery.") AS tempTable";
## Prepare Query
$stmt1 = $dbh->prepare($q1);

$q2 = preg_replace("/^[^\w]*SELECT/i","SELECT FOUND_ROWS() as num_rows,",$tempQuery);
$q2 .= " ORDER BY ".$sort;
$q2 .= " LIMIT ".$offset.",".$limit;
//print $q2;
## Prepare Query
$stmt2 = $dbh->prepare($q2);

try{
    $stmt1->execute();
    $stmt2->execute($params);

}
catch(PDOException $e){
    print $e->getMessage();
}

## Return Results
return $stmt2->fetchAll();

}