Asez Asez - 3 months ago 11
MySQL Question

PHP Progress Bar: % Of 2 Numbers

I have a problem with a Progress Bar percentage. I'm creating a vote system (Yes/No) with a MySQL database and if the 2 numbers together are exceeding 100, the progress bar does not work properly.
http://i.stack.imgur.com/uTpdM.png

All I need It's to 'convert' the numbers to the percentage, even if the votes are exceeding 100. For example, If there are 1000 votes (750 for Yes, 250 for No), the result should be '75% Yes and 25% No'.

Thank you in advance!

<body>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASSWORD', '');
define('DB', 'rating');

$db_connection = new mysqli(HOST, USER, PASSWORD, DB);

$SQL_REQUEST = "SELECT Yes, No FROM `ratings`";

$RESULT = $db_connection->query($SQL_REQUEST);

if($RESULT->num_rows > 0)
{
while($ROW = $RESULT->fetch_assoc())
{
$gp = $ROW['Yes'];
$bp = $ROW['No'];
}
}
?>

<div class="container">
<div class="panel panel-default panel-margin-top">
<div class="transparent">
<div class="panel-heading">
<div class="panel-title">
Rate It
</div>
</div>
</div>

<div class="panel-body">
<div class="progress">
<div class="progress-bar progress-bar-success" style="width:<?php echo $gp ?>%"><?php echo $gp ?>% users voted Yes</div>

<div class="progress-bar progress-bar-danger" style="width:<?php echo $bp ?>%"><?php echo $gp ?>% users voted No</div>
</div>
</div>
</div>
</div>
</body>

Answer

You overwrite the yes, and no on every iteration.

while($ROW = $RESULT->fetch_assoc())
    {
    $gp = $ROW['Yes'];
    $bp = $ROW['No'];
    }

You reassign the value. I'd do:

$gp = 0;
$bp = 0;
while($ROW = $RESULT->fetch_assoc())
    {
    $gp = !empty($ROW['Yes']) ? $gp + 1 : $gp;
    $bp = !empty($ROW['No']) ? $bp + 1 : $bp;
    }

or if $ROW['Yes'] and $ROW['No'] are tinyints....

$gp = 0;
$bp = 0;
while($ROW = $RESULT->fetch_assoc())
    {
    $gp += $ROW['Yes'];
    $bp += $ROW['No'];
    }

Since you only have one row you don't need to loop the fetch.

if($RESULT->num_rows > 0)
   {
        $ROW = $RESULT->fetch_assoc())
        $gp = empty($ROW['Yes']) ? 0 : $ROW['Yes'];
        $bp = empty($ROW['No']) ? 0 : $ROW['No'];
        $yes_vote_average = round(($gp / ($gp + $bp)) ,2) * 100;
        $no_vote_average = round(($bp / ($gp + $bp)), 2) * 100;
   }

then use the $yes_vote_average and $no_vote_average in the <div>...</div> outputs respectively.

Comments