Query Count SQL with percentage in PHP

0

I am making a report and need to count and display the number plus the percentage for the total count. With this code I already count. Is it possible to display the percentage next to it using sql and php?

$sql = "SELECT
    customer.country,
    COUNT(*) AS count
FROM
    customer
INNER JOIN 
    booking ON booking.customer_id = customer.id
WHERE 
    (checkin >= '$datainicialsql' AND checkout <= '$datafinalsql')
GROUP BY country";
$query = mysql_query($sql);

$w = 0;

        while ($result = mysql_fetch_assoc($query))
{
  echo $result['country'] . " - " . $result['count'] . "<br/>";
}

I wanted to do an output like this:

BR 20 (20%)
IT 40 (40%)
PT 40 (40%)
    
asked by anonymous 07.05.2015 / 03:55

1 answer

1

You can iterate through the query result twice. One to calculate the total and another to display the data.

$result = array();
$total = 0;
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row;
    $total += $row['count'];
}
foreach ($result as $row) {
    echo $row['country'] . ' - ' . $row['count'] . ' - (';
    echo (100 * $row['count'] / $total) . '%)<br/>';
}

Another point, I saw that you use the mysql_* functions, but this PHP extension, besides being unsafe, will be discontinued, I suggest using PDO (still without translation)

    
07.05.2015 / 12:48