PHP Prepared语句提取大小

时间:2013-07-11 17:47:52

标签: php mysql mysqli

我正在尝试找到一种方法来获取从PHP使用Select查询时获取的行数。

代码段:

$conn = new mysqli("8.8.4.4", "reader", "youwishyouknew", "perf_test");
if($conn->connect_errno){
    echo 'Failed to connect to Database: ('.$conn->connect_errno.') '.$conn->connect_error;
} else {
    $query = 'SELECT score, date FROM tbl_runs WHERE client_id = '.$_POST['device'].' AND os_id = '.$_POST['os'].' AND test_id = '.$_POST['test'].' ORDER BY date ASC';
    $results = $conn->prepare($query);
    $results->execute();
    $results->bind_results($test_score, $test_date);
    while($results->fetch(){
        $tests[0][] = $test_date;
        $tests[1][] = $test_date;
    }
}

这一切都很好。但我感兴趣的是,如果可以查看实际返回了多少结果而不计算调用fetch()的次数?

3 个答案:

答案 0 :(得分:3)

对于mysqli,您可以使用$results->num_rows

$results = $conn->prepare($query);
$results->execute();
$results->bind_results($test_score, $test_date);
while($results->fetch(){
    $tests[0][] = $test_date;
    $tests[1][] = $test_date;
}
$count = $results->num_rows;

另见http://www.php.net/manual/en/mysqli-stmt.num-rows.php

请记住,在任何MySQL客户端中,在获取所有行之前,结果中的正确行数是未知的。因此,您必须在上面示例中的 while循环之后阅读num_rows

异常:如果在$results->store_result()之后使用execute(),这会使MySQL客户端在内部“下载”所有行,然后后续的fetch()调用只是迭代内部缓存的结果。如果您使用此功能,则可以随时阅读num_rows值:

$results = $conn->prepare($query);
$results->execute();
$results->store_result();
$count = $results->num_rows;
$results->bind_results($test_score, $test_date);
while($results->fetch(){
    $tests[0][] = $test_date;
    $tests[1][] = $test_date;
}

答案 1 :(得分:1)

您可以使用rowCount

$count = $results->rowCount();

答案 2 :(得分:1)

  

可以查看实际返回的结果数量而不计算调用fetch()的次数?

不确定。

$count = count($tests[0]);