为什么$ stmt-> num_rows在MySQL LIMIT之前计算?

时间:2016-12-10 01:49:43

标签: php mysql prepared-statement

我在PHP中执行SQL语句,使用LIMIT $start, $offset对结果进行分页。

意外的障碍是,$stmt->num_rows无论SQL LIMIT如何都会返回所有行。这是我的代码,只是因为我没有犯下一个愚蠢的错误:

$term = '%'.$search.'%'; // I have used htmlspecialchars() above
    $reclimit = 20;
    $start = ($page - 1) * $reclimit;
    $offset = ($page + 2) * $reclimit; // I want to get 60 results in total, or 3 pages of results.

    $mysqli = new mysqli("localhost","username","password","db");

    $stmt = $mysqli->prepare("SELECT title,description FROM content WHERE title LIKE ? LIMIT $start, $offset");

    $stmt->bind_param('s', $term);
    $stmt->execute();

    $stmt->store_result();
    $stmt->bind_result($title, $desc);

    $rowcount = $stmt->num_rows; // This will get all results, regardless of `LIMIT`
    $tpages = ceil($rowcount / $reclimit); // $rowcount returning incorrect integer messes up my pagination

    echo $start;
    echo $offset;
    echo $rowcount;
    echo $tpages; // Testing all variables to see which was the culprit

    $wcount = 0;
    $wmax = 20;

    while(($stmt->fetch()) and ($wcount < $wmax))
    {

        // Echoing HTML --snipped--

        $wcount++;
    }

    $stmt->close();

    $mysqli->close();
    }

我无法看到我做错的任何事情,看起来很奇怪$rowcount会返回所有返回行的值,无论LIMIT是什么,因为返回的数据已经在调用总和之前有限。我误解了什么吗?

感谢您的时间

0 个答案:

没有答案