PHP / MySQL计数Num行

时间:2013-03-03 18:41:59

标签: php mysql

我有以下PHP代码:

$sql   = new mysqli(/*connection info/db*/);
$query = $sql->$query("SELECT * from users WHERE /* rest of code */);

我现在想知道是否有任何方法可以检索上述查询找到的行数...

3 个答案:

答案 0 :(得分:2)

你应该考虑使用PDO,它更安全,更面向对象的方法:

$database = new PDO(/*connection info/db*/);

$statement = $database->prepare('SELECT FROM fruit WHERE fruit_id = ? AND name = ?');
$statement->bindValue( 1, 'fruit_id_value' );
$statement->bindValue( 2, 'Banana' );
$statement->execute();

$count = $statement->rowCount(); # <-- The row count you are looking for!

- &GT;访问http://php.net/manual/en/pdostatement.rowcount.php了解更多信息

答案 1 :(得分:0)

在Mysqli中我知道你可以做到

printf("Number of rows: %d.\n", $sql->num_rows);

这是所有代码

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

我从这本php手册http://php.net/manual/en/mysqli-stmt.num-rows.php

中得到了这个

答案 2 :(得分:0)

SELECT查询有一个修饰符,它包含您需要的计数信息:SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS  * from users WHERE /* rest of code */

运行该查询后,您可以运行SELECT FOUND_ROWS();获得最终的行数。

如果你需要的只是计数,你可以做到

SELECT count(*) from users WHERE /* rest of code */