Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could order by category and then name (<em>make sure you have an index on category, name</em>) Your Query would be:</p> <pre><code>SELECT * FROM `workouts` ORDER BY category, name </code></pre> <p>Then when you iterate you check if the category changed and if, close the sublist and open a new one showing the category first.</p> <p>Another, slightly cleaner Solution would be to iterate twice, using the first loop to sort in an associative array by category:</p> <pre><code>$sth = $dbh-&gt;prepare("SELECT * FROM workouts"); $sth-&gt;execute(); $workouts = array(); /* First Loop */ while(($result = $sth-&gt;fetch(PDO::FETCH_ASSOC)) !== FALSE) { $workouts[$result['category']][] = $result; } </code></pre> <p>Now you can loop over $workouts, using the key as the Category.</p> <pre><code>foreach($workouts as $category =&gt; $workoutsByCategory) { //display category and start subset foreach($workoutsByCategory as $workout) { //display workout } } </code></pre> <p>It would be a lot cleaner thou to use a second table which holds the category names and use the id of that table in your workouts table to connect. You can then get the results using join. You might want to look into Relational Database Design and <a href="http://en.wikipedia.org/wiki/Database_normalization" rel="nofollow">Normalization</a></p> <p>Example (not tested) Table Layouts:</p> <pre><code>table "workouts" id | category_id | title | description | hashtags | video | seen | date_published table "categories" id | title </code></pre> <p>Then you can get the results using:</p> <pre><code>SELECT workouts.*, categories.title as category_title FROM workouts LEFT JOIN categories ON (category.id = workouts.category_id) </code></pre> <p>This will make it easier to change the name of a category amongst other advances ... but you'll read up on that i guess.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload