Count SQL query with PHP percentage

Asked

Viewed 435 times

0

I’m making a report and I need to count and display the number plus the percentage for the total count. With this code I already count. It is possible to display the percentage beside 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 make an output like this:

BR 20 (20%)
IT 40 (40%)
PT 40 (40%)
  • Although it’s possible to do it in one query I do not think it will be very efficient. I suggest, alternatively, that you consult first to get the total records. Then use this value, together with the result of the second query, to calculate the percentage.

1 answer

1


You can iterate twice the query result. One to calculate the total and one 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 functions mysql_*, but this PHP extension is not only unsafe, it will be discontinued, I suggest using the extension PDO (still without translation)

  • The solution is very good. Thank you. Regarding PDO. You have an idea of when the solution will be discontinued?

  • in accordance with the documentation: "This extension has become obsolete in PHP 5.5.0 and will be removed in the future"

  • The percentage output is not showing up. Now that I populated the table I noticed.

  • BR - 48 - (0%) CL - 2 - (0%) ES - 2 - (0%) FR - 4 - (0%) GB - 2 - (0%) IT - 6 - (0%) EMPTY - 2 - (0%)

  • Solved :D echo (100 * $Row['Count'] / $total) . '%)<br/>';

  • updated the reply

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.