Adrian Adrian - 26 days ago 7
PHP Question

Calculate percentage of ENUM type column with PHP

In my SQL database I have one table with some items with a column that are ENUM type and has 3 options: 'pending', 'discount', 'received'

How can I print the population percentage of 'received' option, like (In my table I have 40% of 'received' option that are selected) ?

Thank you!

Answer

To get the totals for each is pretty simple (assuming your enum column is called 'status' and has a column called id):

SELECT status, count(id) FROM myTable GROUP BY status;

While it would be possible to write your query to calculate the actual percentages, the simplest thing from there is to do the math yourself (I'm not going to go through the php rigamarole of executing the query, I just assume you have a result something like ['pending' => 100, 'discount' => 200, 'received' => 50]):

$total = $result['pending'] + $result['discount'] + $result['received'];
$pctPending = ($result['pending']*100)/$total;

ans so forth. You will of course have to adjust the code to match how your results come back, but the math applies regardless.

Comments