简体   繁体   中英

How to add up votes in a table and display it on screen

i have a php code which selects and shows data from my 'elections' table. i have another table called 'votes' which contains all the votes by users. how do i select the two tables and show the party that has had the most votes? so if labour had 5 votes for example and lib dems had 3 votes, how would i show on screen that 'labour has won this election with __ votes? my php is as follows:

    <?php
$id = $_GET['election'];
$result = mysql_query("SELECT election_id, name_of_election, date, month, year FROM elections WHERE election_id = '$id'")
or die(mysql_error()); ;

if (mysql_num_rows($result) == 0) {
       echo '<hr><h3>There Aren\'t Any Elections Setup Yet</h3><hr> ';
    } else {

        echo '<hr><h3>Vote Count</h3><hr>';


while($info = mysql_fetch_array($result))
{
        echo "<tr>";
        echo "<td>" . $info['name_of_election']. "</td>";
        echo "<br/><br/><td>" . $info['date']. ' '. $info['month']. ' ' . $info['year']. "</td>";
        echo "<br/><br/><td>" . '<hr>' .  "</td>";


}
    }
echo "</tr>";
echo "</table>";
?>

my database table consists of the following fields:

(dont ask about the date fields)

elections: election_id, name_of_election, date, month, year, party1, party2, party3, status

votes: vote_id, election_id, ni, party

any ideas?

This will give you the party and count for selected election in descending order of count:

$result = mysql_query(
    sprintf("
        SELECT votes.party, COUNT(votes.vote_id)
        FROM votes
        WHERE election_id = %d
        GROUP BY election_id, votes.party
        ORDER BY COUNT(votes.vote_id) DESC",
        mysql_real_escape_string($id)
    )
);

Edit: To display the first row (which will be the party with the most votes):

list($party, $votes) = mysql_fetch_row($result);
echo '<p>'.$party.' won with '.$votes.'</p>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM