2013-05-21 42 views
0

我已經統計了投票給某個候選人的選民的數量,我想要顯示哪一個獲得了最高的投票數。我試圖將它們存儲在變量,這樣我就可以使用MAX()方法,但我得到了錯誤「未定義」 .ANY幫助,請PHP從mysql表中獲得最大數量

<?php 
$query="select count(*) as total from voting Where ca_id=1"; 
    //ca_id is the candidate id that voter choose 
$result = mysql_query($query); 
$row = mysql_fetch_assoc($result); 
echo"$row[total]<br>"; 


$query="select count(*) as total2 from voting Where ca_id=2"; 
$result = mysql_query($query); 
$row2 = mysql_fetch_assoc($result); 
echo"$row2[total2]<br>"; 

$query="select count(*) as total3 from voting Where ca_id=3"; 
$result = mysql_query($query); 
$row3 = mysql_fetch_assoc($result); 
echo"$row3[total3]<br>"; 

$query="select count(*) as total4 from voting Where ca_id=5"; 
$result = mysql_query($query); 
$row4 = mysql_fetch_assoc($result); 
echo"$row4[total4]<br>"; 



?> 
+4

[請不要在新代碼中使用'mysql_ *'函數](http://bit.ly/phpmsql)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[紅框](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 –

+0

如果您設置[SQL小提琴](http://sqlfiddle.com/) –

+0

將您的值轉儲到數組並使用asort()或arsort() – Dave

回答

3
SELECT count(1) co, ca_id FROM voting GROUP BY ca_id ORDER BY co DESC LIMIT 5 
2

你並不需要執行四個查詢此。你可以只使用一個查詢。在你的情況,你可以這樣做:

select ca_id, count(*) as counter from voting group by ca_id order by counter desc 

你還可以用一個單一的查詢得到您的結果

如前所述,PDO是在這種情況下,你的數據庫相關的調用一個更好的選擇

+0

我有不同的ID,他們不止一次地重複 所以我想要統計每個ID的重複次數 – Suma

2

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box ? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.

你可以使用類似於MySQLi擴展的東西。

<?php 

$mysqli = new mysqli('host', 'user', 'pass', 'db'); 

$sql = "SELECT COUNT(votes) as vote_count, ca_id as candidate_id FROM voting GROUP BY ca_id ORDER BY vote_count DESC"; 
$result= $mysqli -> query($sql); 

// Error Checking 
if($mysqli -> error){ 
    echo 'Error: '.$mysqli -> error; 
    exit; 
} 

while($row = $result -> fetch_object()){ 

    // Print out each candidate ID and the amount of votes they had. 
    echo 'Candidate ID: '.$row -> candidate_id.', Votes: '.$row -> vote_count.'<br/>'; 

    // If you want to just show the highest voted candidate - put the data in an array 
    $votes[$row -> vote_count] = $row -> candidate_id; 

} 

echo max(array_keys($votes)); 

這也將減少你的運行下降到只有1

+0

我得到這個錯誤 致命錯誤:致電給會員在非對象上函數fetch_object() – Suma

+0

您是否更改了數據庫連接設置,以便它們連接到您的數據庫?另外,我添加了幾行,可以打印出任何錯誤信息。 – ajtrichards

0

首先使用組的查詢量來檢索一個查詢所有的數據,而不是查詢每個考生:

SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id 

如果你需要一個頂級投ID使用:

SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id SORT BY total 
DESC LIMIT 1 

注意:不是最有效的使但是會更快,然後查詢每個ca_id。

+0

我使用了這個「SELECT ca_id,count(*)作爲總數有投票GROUP BY ca_id」,但是它沒有給出每個候選人的總投票數「我有5個候選人」。 – Suma