使用html表来命令sql查询

时间:2015-03-29 23:27:09

标签: php html sql

我必须按字母顺序按艺术家和专辑组织一个结果表,然后按曲目编号跟踪。我不知道如何解决这个问题,任何建议都会有所帮助。这就是我到目前为止所做的:

$dbQuery=$db->prepare("select tracks.title, albums.title, artists.name, 

basket.id ".
                      "from basket,tracks,albums,artists ".
                      "where basket.userID=:userID ".
                      "and basket.paid='Y' ".
                      "and basket.trackID=tracks.id ".
                      "and albums.id=tracks.albumID ".
                      "and artists.id=tracks.artistID");


$dbParams = array('userID'=>$_SESSION["currentUserID"]);                      
$dbQuery->execute($dbParams);
$numTracks=$dbQuery->rowCount();

if ($numTracks==0)
   echo "<h3>You have not made any purchases</h3>";
else {

?>

   <h2>Your Purchase History</h2>

   <table style="margin-left:15px">
   <tr><th>Artist</th><th>Album</th><th>Track</th></tr>

<?php 

   while ($dbRow=$dbQuery->fetch(PDO::FETCH_NUM)) {

      echo "<tr><td>$dbRow[2]</td><td>$dbRow[1]</td><td>$dbRow[0]</td><td>$dbRow[3]</td></tr>";
   }
}
?>

</table>
</body>

我不确定在输出到html表之前如何在查询中执行这么多订单

编辑:我无法通过工作获得订单,但事实证明我的查询存在语法问题,因为它的附加方式有效:

“按...排序

这没有 “按顺序排列

1 个答案:

答案 0 :(得分:1)

只需在查询结尾添加order by fields(ASC or DESC) you want, separated by comma个参数:

select tracks.title, albums.title, artists.name, basket.id
from table_name
....
order by tracks.title, albums.title, artists.name, basket.id

order by 1,2,3,4 -- or 2,1,3,4 or 4,1,3,2 or etc

您还可以按顺序添加asc(对于默认的升序)和dsc(对于降序)在列前面。