2015-04-02 67 views
-1

我有這樣的代碼獲得多少結果也有在結果中有一列:PHP和MySQL - 獲取的具體結果數

$result = "SELECT name FROM users"; 

echo $result; 

如何顯示一定數量的特定的串?例如,我想在「名稱」列中搜索名稱「Andrew」。有20條結果適用於「Andrew」。我如何迴應「20」?

+0

我沒有做的downvoting但是,作爲一個頭,我敢肯定,這個人做到了因爲這是一個非常「Google」的問題。谷歌搜索「計數結果sql」本來會給你答案,很可能甚至鏈接到已發佈在SO上的問題。 – 2015-04-02 20:39:30

回答

2

你會COUNT他們:

$result = "SELECT COUNT(`name`) AS `NameCount` FROM `users` WHERE `name` = 'Andrew'"; 

對於所有的名字,你可以這樣做:

SELECT `name`, count(`name`) AS `NameCount` 
FROM `users` 
GROUP BY `name` 

這會導致這樣的事情:

name | NameCount 
---------------------- 
Andrew |   20 
Bob  |   6 
Carol |   125 
0

如果要使用Mysqli,你可以使用$ num_rows。 Somelithing像:

<?php 
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); 

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

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) { 

    /* determine number of rows result set */ 
    $row_cnt = $result->num_rows; 

    printf("Result set has %d rows.\n", $row_cnt); 

    /* close result set */ 
    $result->close(); 
} 

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

也,你可以使用mysql count()函數,如:

$result = "SELECT count(*), name FROM users";