Jump to content

Show a percentage based on values from a table


AndyJones

Recommended Posts

Hi there,

I have inherited a site, and am not very good with PHP so please forgive me!

It's a simpel voting system, where people vote for A B or C.

I have the following php on a page, which looks in a table, pulls the 'total' for each row (vote) and displays then on a page so we can see how many votes were given to A, B or C.

<?php
$stmt = $modx->prepare("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$output = [];

foreach ($rows as $row) {
    $output[] = $row['option'] . ' has ' . $row['total'] . ' votes';
}

return implode('<br><br>', $output);

So the ooutut is currently:

 

A has 10 votes

B has 30 votes

C has 40 votes

 

 

I would like to be able to put a percentage next to each number of 'votes' - so that the user can see the percentage of all the votes so far.

e.g.

A has 10 votes (12.5%).

B has 30 votes (37.5%).

C has 40 votes (50%).

I hope the above makes sense!

Thanks in advance for a steer in the rirght direction - I just don't know PHP well enough to work out the syntax etc.

 

Link to comment
Share on other sites

what value do you need to calculate the percentage, the total number of votes? you just need to devise a method of getting that value from the fetched data in $rows. one method would be to loop over the data to add up the individual totals. another method would be to use php's array functions to operate on the data as a set - see php's array_column() and array_sum().

Link to comment
Share on other sites

How about this?

$stmt = $modx->prepare("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");
if ($stmt->execute())
{
	$sum = 0;
	$output = array();
	while($row == $stmt->fetch(PDO::FETCH__ASSOC))
	{
		$sum += $row['total'];
		$output[] = $row;
	}
	foreach ($output as $line)
	{
		$pct = number_format(($line['total'] / $sum)*100, 2);
		echo $line['option'] . ' has ' . $line['total'] . " votes (%$pct)<br><br>";
	}
}
else
	echo "Query did not execute";

Did not test.

Link to comment
Share on other sites

or...

$res = $pdo->query("SELECT `option`, total FROM vote");
$data = $res->fetchAll();
$votes_cast = array_sum( array_column($data, 'total') );
foreach ($data as $r) {
    printf ("%s has %d votes (%0.1f %%)<br>", $r['option'], $r['total'], $r['total']*100/$votes_cast);
}          

 

  • Like 2
Link to comment
Share on other sites

On 6/9/2022 at 5:51 PM, ginerjm said:

Oops.  youll have to play with the % sign.  I put it in the wrong place.

" votes (" . $pct .  "%)<br><br>";

 

Thanks for this - I'll have a play aroudn with it in the morning!

Will report back!

 

Andy

Link to comment
Share on other sites

On 6/9/2022 at 7:45 PM, Barand said:

or...

$res = $pdo->query("SELECT `option`, total FROM vote");
$data = $res->fetchAll();
$votes_cast = array_sum( array_column($data, 'total') );
foreach ($data as $r) {
    printf ("%s has %d votes (%0.1f %%)<br>", $r['option'], $r['total'], $r['total']*100/$votes_cast);
}          

 

Ah thanks - will have a play with this too.

 

Thanks for your input and advice!

Link to comment
Share on other sites

On 6/9/2022 at 5:41 PM, ginerjm said:
->

 

On 6/9/2022 at 5:41 PM, ginerjm said:

How about this?

$stmt = $modx->prepare("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");
if ($stmt->execute())
{
	$sum = 0;
	$output = array();
	while($row == $stmt->fetch(PDO::FETCH__ASSOC))
	{
		$sum += $row['total'];
		$output[] = $row;
	}
	foreach ($output as $line)
	{
		$pct = number_format(($line['total'] / $sum)*100, 2);
		echo $line['option'] . ' has ' . $line['total'] . " votes (%$pct)<br><br>";
	}
}
else
	echo "Query did not execute";

Did not test.

So I tried your solution but it throws a 500 internal server error?

I've played aroudn, but I can't get it working. Any ideas?

This is what I used:

$stmt = $modx->prepare("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");
if ($stmt->execute())
{
	$sum = 0;
	$output = array();
	while($row == $stmt->fetch(PDO::FETCH__ASSOC))
	{
		$sum += $row['total'];
		$output[] = $row;
	}
	foreach ($output as $line)
	{
		$pct = number_format(($line['total'] / $sum)*100, 2);
		echo $line['option'] . ' has ' . $line['total'] . " votes (" . $pct .  "%)<br><br>";
	}
}
else
	echo "Query did not execute";

 

Link to comment
Share on other sites

On 6/9/2022 at 7:45 PM, Barand said:

or...

$res = $pdo->query("SELECT `option`, total FROM vote");
$data = $res->fetchAll();
$votes_cast = array_sum( array_column($data, 'total') );
foreach ($data as $r) {
    printf ("%s has %d votes (%0.1f %%)<br>", $r['option'], $r['total'], $r['total']*100/$votes_cast);
}          

 

So I just had a play with this - but I don't really understand what to to do with your code at all - it doesn't resemble mine enough to know what to replace.

Link to comment
Share on other sites

10 hours ago, ginerjm said:

The error in my code is the double equal in the whille line.

As for Barand's code, just run it and see what it gives you.

Thank you. I changed the double Eqaals to a single, but it's still showing a 500 server error.

I ran Barand's code, but it doesn't connect to the database table - so wondering if it was supposed to go with some of the existing code.

This is what I have now:

 

<?php
$stmt = $modx->prepare("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");
if ($stmt->execute())
{
	$sum = 0;
	$output = array();
	while($row = $stmt->fetch(PDO::FETCH__ASSOC))
	{
		$sum += $row['total'];
		$output[] = $row;
	}
	foreach ($output as $line)
	{
		$pct = number_format(($line['total'] / $sum)*100, 2);
		echo $line['option'] . ' has ' . $line['total'] . " votes (" . $pct .  "%)<br><br>";
	}
}
else
	echo "Query did not execute";
	

 

10 hours ago, Barand said:

I think that was a bit harsh to be fair - as I said I've picked this up to help someone out, and I don't know PHP. It would be a huge learning curve and would take many hours of learning to figure this out - when I'm just trying to help someone out - hence why I came here for advice.

 

Link to comment
Share on other sites

1 hour ago, AndyJones said:
$stmt = $modx->prepare("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");

 

On 6/9/2022 at 7:45 PM, Barand said:
$res = $pdo->query("SELECT `option`, total FROM vote");

@AndyJones If you compare the above 2 lines you will see that my PDO connection is $pdo whereas yours is $modx.

Just change my $pdo to $modx to use your connection.

Link to comment
Share on other sites

59 minutes ago, Barand said:

 

@AndyJones If you compare the above 2 lines you will see that my PDO connection is $pdo whereas yours is $modx.

Just change my $pdo to $modx to use your connection.

Ahah - bingo - thank you so much!

Thjis is the final code that works:

<?php
$res = $modx->query("SELECT * FROM `modx_ltda_vote` ORDER BY `option` ASC");
$data = $res->fetchAll();
$votes_cast = array_sum( array_column($data, 'total') );
foreach ($data as $r) {
    printf ("%s has %d votes (%0.1f %%)<br>", $r['option'], $r['total'], $r['total']*100/$votes_cast);
}          

Thanks again _ will endevor to learn this stuff - but just needed a quick help out as it's something I need to get live for a friend.

Cheers

Andy

Link to comment
Share on other sites

the last issue above, the mismatched variable names, would have been producing php errors. is php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php would help you by reporting and displaying all the errors it detects?

Edited by mac_gyver
Link to comment
Share on other sites

Just now, mac_gyver said:

that last issue above, the mismatched variable names, would have been producing php errors. is php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php would help you by reporting and displaying all the errors it detects?

Hmm OK - I'll go check. Thanks.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.