Percentage vote in php within a while

2

I need to get the votes of the candidates that are in mysql and generate the percentage of votes that each had. How can I view the result since it is within a while?

$sql =  mysql_query("SELECT * FROM candidatos ORDER BY nome_candidato");
while($ca = mysql_fetch_array($sql)){
$id_candidato = $ca['id_candidato'];
$nome_candidato = $ca['nome_candidato'];
$votos = $ca['votos'];
}
    
asked by anonymous 18.04.2018 / 00:19

2 answers

3

You can change your SELECT to do this automatically. See:

SELECT id_candidato, nome_candidato, votos, votos * 100 / t.s AS 'total'
FROM candidatos
CROSS JOIN (SELECT SUM(votos) AS s FROM candidatos) t ORDER BY nome_candidato

See it working

Then just use:

$id_candidato = $ca['id_candidato'];
$nome_candidato = $ca['nome_candidato'];
$votos = $ca['votos'];
$total = $ca['total'];

Your code looks like this:

$sql =  mysql_query("SELECT id_candidato, nome_candidato, votos, votos * 100 / t.s AS 'total'
FROM candidatos
CROSS JOIN (SELECT SUM(votos) AS s FROM candidatos) t ORDER BY nome_candidato");
while($ca = mysql_fetch_array($sql)){
   $id_candidato = $ca['id_candidato'];
   $nome_candidato = $ca['nome_candidato'];
   $votos = $ca['votos'];
   $total = $ca['total'];
}
    
18.04.2018 / 00:41
1

You already have the number of votes for each one, now add these quantities to know the toral and find out the percentage:

$sql =  mysql_query("SELECT * FROM candidatos ORDER BY nome_candidato");

$total = 0;
while($ca = mysql_fetch_array($sql)){
    $id_candidato = $ca['id_candidato'];
    $nome_candidato = $ca['nome_candidato'];
    $votos = $ca['votos'];
    $total += $ca['votos'];
}

When you want to show the results, do the following:

$umporcento = $total / 100;

$porcentagem = $umporcento * $votos;
    
18.04.2018 / 00:41