I need to order the mysql query by total score which is stored in a variable/array. I understand a foreach loop is basically performing the query for each result, so ORDER BY won’t work. How can I order the query results by score?
<?
if (isset($_POST['submit'])) {
$total = array();
foreach($_POST["category"] as $key => $value):
if(!array_key_exists($value,$total)): $total[$value] = ""; endif;
$total[$value] += $_POST["answer"][$key];
endforeach;
$i = 1;
foreach($total as $cat => $score):
$getData = mysql_query("SELECT * FROM lt_category WHERE cat_id = '$cat' ORDER BY {$score} DESC");
if($getData === FALSE) {
die(mysql_error());
}
else {
while ($result = mysql_fetch_array($getData)) { ?>
<div class="result <? echo $result['name']; ?>">
<span class="category"> <? echo $i . "." . $result['name'] . "." . $score; ?> </span>
<span class="desc"> <? echo $result['desc']; ?> </span><!-- description of category -->
</div>
This code does not return any errors, but it doesn’t order by score either.
I’m not sure how many questions or categories you are dealing with but you should avoid looped queries when you can. Something like this might be an option.
<?php
if (isset($_POST['submit'])){
$data = array();
//desc is a reserved word in php. Use back ticks.
$sql = "SELECT cat_id, name, `desc` FROM lt_category";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$data[$row['name']]['name'] = $row['name'];
$data[$row['name']]['desc'] = $row['desc'];
}
$total = array();
foreach($_POST["category"] as $key => $value):
if(!array_key_exists($value,$total)): $total[$value] = ""; endif;
$total[$value] += $_POST["answer"][$key];
endforeach;
$i = 1;
arsort($total);
foreach($total as $cat => $score):
?>
<div class="result <?php echo $data[$cat]['name']; ?>">
<span class="category"> <?php echo $i . "." . $data[$cat]['name'] . "." . $score; ?> </span>
<span class="desc"> <?php $data[$cat]['desc']; ?> </span><!-- description of category -->
</div>
<?php
$i++;
endforeach;
}
?>
Can you tell me why I should move from mysql queries to PDO? I haven’t done anything from scratch with PHP for a long time, so I’m out
of the loop with the latest.