duandeng7132 2014-02-24 04:17
浏览 41
已采纳

MySQL和HTML:根据特定值排序行[重复]

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>
  • 写回答

2条回答 默认 最新

  • dsndm82062 2014-02-24 04:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示