1

I have to organise a table of results by artist and album alphabetically, then track by track number. I have no idea how to go about this, any suggestions would be helpful. This is what i have so far:

$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>

I'm not sure how to do so many orders in the query before it outputs to the html table

EDIT: I couldn't get the order by to work, but turns out i was having syntax issues with my query the way it was appended this worked :

" order by...

This didn't "order by

3
  • Why didn't you tag this PHP? Commented Mar 29, 2015 at 23:28
  • 2
    Look up the ORDER BY statement for SQL. Commented Mar 29, 2015 at 23:28
  • generally ordering is done on the database itself. E.g. select id from user order by id DESC; Commented Mar 29, 2015 at 23:31

1 Answer 1

1

just add order by fields(ASC or DESC) you want, separated by comma statment to end of your query:

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

or

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

you can also add asc (for ascending order which is default) and dsc (for descending order) in front of columns in order by clause.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.