How can PHP developers efficiently count and aggregate votes from a database for survey results?

To efficiently count and aggregate votes from a database for survey results, PHP developers can use SQL queries to retrieve the data and then process it in PHP to calculate the totals. By using SQL's aggregate functions like COUNT() and GROUP BY, developers can efficiently summarize the survey results without needing to loop through each individual record.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "survey_db";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to count and aggregate votes
$sql = "SELECT option, COUNT(*) as total_votes FROM survey_results GROUP BY option";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output the aggregated results
    while($row = $result->fetch_assoc()) {
        echo "Option: " . $row["option"]. " - Total Votes: " . $row["total_votes"]. "<br>";
    }
} else {
    echo "No results found";
}

$conn->close();