This question already has an answer here:
I'm working on a little downloads area of a website where people can submit different themes, and the community can rate them with a + or - 1 (very similar to Stack Overflow).
I currently am pulling data from a MySQL database - much of that isn't terribly important to the question - but here is what my final code and table looks like:
while($record = mysql_fetch_array($myData)){
echo '<tr>';
echo '<td>' . $record['votes'] . '</td>';
echo '<td>' . $record['name'] . '</td>';
echo '<td>' . $record['author'] . '</td>';
echo '<td>' . $record['description'] . '</td>';
echo '</tr>';
}
I would like to order each table row based on the value of the <td>
called votes
. I understand this is a bit broad since I don't have code supplied, but I've searched the web and found nothing about what I'm attempting to do. I'm sure it can be done by modifying the while
function, but I'm not sure how.
If it proves to be any help, my full PHP code is below:
<?php
$con = mysql_connect('host','name','password');
mysql_select_db('database',$con);
$sql = "SELECT * FROM themer";
$myData = mysql_query($sql,$con);
echo '<table>';
while($record = mysql_fetch_array($myData)){
echo '<tr>';
echo '<td>' . $record['votes'] . '</td>';
echo '<td>' . $record['name'] . '</td>';
echo '<td>' . $record['author'] . '</td>';
echo '<td>' . $record['description'] . '</td>';
echo '</tr>';
}
echo '</table>';
?>
EDIT: I apparently was searching for the wrong stuff when I researched this - I didn't know mySQL had the functionality described in the answers below. Now that I know what was up, this might be a possible duplicate - mysql query order by multiple items
</div>
The simplest option is to pass the responsibility down to the database level. This is also most likely the best option since you can then add an index; database engines are quite good at querying and ordering results. Add an ORDER BY
clause to your query, making your query:
SELECT *
FROM themer
ORDER BY votes
To order this from highest to lowest, you'll need to reverse the sort order. Do this by adding a DESC
keyword:
SELECT *
FROM themer
ORDER BY votes DESC
Note: new code should really not be using the mysql_
PHP functions anymore. They are deprecated, and for good reason. Good alternatives include mysqli and PDO.
$sql = 'SELECT * FROM themer
ORDER BY ABS(votes) DESC';