R.m R.m - 1 year ago 44
MySQL Question

Display sum of 2 mysql colums in php

I'm trying to do this simple sum of two boolean columns in a mysql database. And make a results pane with different calculations on these 2 values.
This is how the db looks like db

I'm trying to come up with a mysql statement that returns the sum of 'liked' and the sum of 'disliked'

Then I need to have this value in 2 formats:

  • as an integer (just the count)

  • as a percentage

This is how my php code looks like:

$get_votes = 'SELECT liked SUM(1), disliked SUM(1) AS total FROM live';
$run_votes = mysqli_query($con, $get_votes);
$row_votes = mysqli_fetch_array($run_votes);

$disliked = $row_votes['disliked']
$liked = $row_votes['liked'];

$count = $disliked+$liked;

$per_disliked = round($disliked*100/$count) . "%";
$per_liked = round($liked*100/$count) . "%";

$per_dislikedclean = round($disliked*100/$count);
$per_likedclean = round($liked*100/$count);

I'm getting a 'division by zero' error. This is probably because mysqli_fetch_array expects a mysqli_result. Can anyone shed a light on this topic ?

Answer Source

Try below SQL to get your desired result

SELECT SUM(liked) As liked, SUM(disliked) AS disliked, ( SUM(liked)*100 )/count(*) AS like_perc, ( SUM(disliked)*100)/count(*) AS dislike_perc FROM live