1

我有以下 PHP 代码:

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

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

4

3 回答 3

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!

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

于 2013-03-03T18:53:43.620 回答
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

于 2013-03-03T18:44:30.420 回答
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 */
于 2013-03-03T19:02:09.137 回答