Percentage of vote in php within a while

Asked

Viewed 106 times

2

I need to take the votes of the candidates that are in mysql and generate the percentage of votes that each one had. How can I view the result since it is inside 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'];
}
  • What comes inside of $ca['votos'] ? How the table is structured candidatos ?

  • $votes = one of voters who voted for the candidate

  • The table is pretty simple... id, nominee, and votes... that’s it.

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 working

Then just use it:

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

Your code will look 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'];
}
  • 1

    Take advantage, and also include the order to match the question

  • @Isac thank you!

  • 1

    Was perfect!!

  • 1

    Thank you all very much!

  • 1

    @Andrémonjardim does not forget to approve

1

You already have the amount of votes of each, now add these amounts 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 showing the results do the calculation:

$umporcento = $total / 100;

$porcentagem = $umporcento * $votos;
  • I had also thought to do so! = ) It works too.

  • 1

    But it’s more lines. It’s a matter of where you want to leave the work, bank or PHP

  • Exactly! I particularly prefer with the bank. I just don’t do it when I can’t.

  • Whenever I can leave this part to the front-end (javascript)

  • It’s a good one too!

  • It was perfect with your help!! Thanks anyway!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.