2013-03-03 67 views
1

我有下面的PHP代碼:PHP/MySQL的計數NUM行

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

我現在想知道是否有什麼辦法可以檢索上面的查詢中發現的行量...

+1

[mysqli_result :: $ NUM_ROWS](http://php.net/manual/en/mysqli-result.num-rows。 PHP) – insertusernamehere 2013-03-03 18:44:28

回答

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

你應該考慮使用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更多信息

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 */