My PHP is of a standard now that needs to be lifted to the next level - I can make things work, but I know there's a better way to do it - however I'm not sure where to start.
My problem is this, which is some PHP code to read data from an online poll and display a bar chart. It makes an SQL call, calculates the percentage and length of each bar and passes that to the CSS to draw the bars. It works great - but it's not pretty, and I know there's a way to make just one SQL call to build an array of some kind, then loop through the array performing the calculations and presenting the HTML. At the moment there's 4 identical functions being performed at each stage - there must be a way to build a function or a class to handle this... but my OOP is not great!
If someone could point me in the right direction, either with some revised code or somewhere I can read up on this kind of OOP or array looping I'd be grateful!
Thanks
Code: Select all
<?php
$sql = mysql_query("SELECT COUNT(*) FROM question1 WHERE answer='1'");
$count1 = mysql_fetch_row($sql);
$count1 = $count1[0];
$sql = mysql_query("SELECT COUNT(*) FROM question1 WHERE answer='2'");
$count2 = mysql_fetch_row($sql);
$count2 = $count2[0];
$sql = mysql_query("SELECT COUNT(*) FROM question1 WHERE answer='3'");
$count3 = mysql_fetch_row($sql);
$count3 = $count3[0];
$sql = mysql_query("SELECT COUNT(*) FROM question1 WHERE answer='4'");
$count4 = mysql_fetch_row($sql);
$count4 = $count4[0];
$total = $count1 + $count2 + $count3 + $count4;
$count1 = ($count1 / $total);
$count1pc = round($count1 * 100);
$bar1 = round($count1 * 200);
$count2 = ($count2 / $total);
$count2pc = round($count2 * 100);
$bar2 = round($count2 * 200);
$count3 = ($count3 / $total);
$count3pc = round($count3 * 100);
$bar3 = round($count3 * 200);
$count4 = ($count4 / $total);
$count4pc = round($count4 * 100);
$bar4 = round($count4 * 200);
print '<div class="answer_item"><div class="answer_title">Answer 1: </div><div class="bar" style="background-color: #D84848; width: ' . $bar1 . 'px;"></div><div class="pc">'.$count1pc.'%</div></div>';
print '<div class="answer_item"><div class="answer_title">Answer 2: </div><div class="bar" style="background-color: #CDC42B; width: ' . $bar2 . 'px";></div><div class="pc">'.$count2pc.'%</div></div>';
print '<div class="answer_item"><div class="answer_title">Answer 3: </div><div class="bar" style="background-color: #0F7794; width: ' . $bar3 . 'px;"></div><div class="pc">'.$count3pc.'%</div></div>';
print '<div class="answer_item"><div class="answer_title">Answer 4: </div><div class="bar" style="background-color: #E4802B; width: ' . $bar4 . 'px;"></div><div class="pc">'.$count4pc.'%</div></div>';
?>