Pie chart based on checkbox array

Hi i would like to make a pie chart based on checkbox array submitted from the form where you can select more than 1 choice.
this is the form

<form method="post" action="" >
<input type="checkbox" value="ice cream" name=" food[] ">ice cream
<input type="checkbox" value="chocolate" name=" food[] ">chocolate
<input type="checkbox" value="milkshake" name=" food[] ">milkshake
<input type="checkbox" value="cake" name="food[] ">cake.

in the database the values are posted just fine and correctly.the only thing i need is how to present the choices that is how many times ice cream was chosen or cake. Please help me

How are the values being stored in your database?

if i choose two choices.in the database column it will be(cake,ice cream) if one of it it will be just be cake.
so the choices are separated by comma.

@cielonovatus95 welcome to the forums. When you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the code block.

thank u

I suspected as much. This will make it more difficult to count the number of each. It can be done, but it’s a bit of a pain.

I would strongly recommend you take a look at Normalizing your database. It would make the process a lot easier.

If you insist on storing a comma separated string, you’ll have to retrieve every row of your database table and do some parsing to get the totals:

All code in this post is untested, i’m just pulling it from my head for example sake.

$foodstore = array();
$dbquery = mysqli_query($db,"SELECT food FROM mytable");
while($row = mysqli_fetch_array($dbquery)) {
  $food = explode(",",$row['food']);
 foreach($food AS $fin) {
   if(array_key_exists($fin,$foodstore) {
     $foodstore[$fin] += 1;
   else {
     $foodstore[$fin] = 1;
echo $foodstore["cake"]

Whereas, if you had normalized the database, it goes a little simpler…and we can use some fancyness.

$foodstore = array();
$dbquery = mysqli_query($db,"SELECT COUNT(name) AS c, name FROM desserts GROUP BY name");
array_walk(mysqli_fetch_all($dbquery,MYSQL_ASSOC), function(v,i) { $foodstore[$v['name']] = $v['c']; });
echo $foodstore['cake'];
1 Like

@m_hutley Thank you so much it worked

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.