Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In this many-to-many scenario you describe, you can't avoid duplicate data in any single result set you get.</p> <p>Here's an idea. Do a separate query to build an array of category names, with their database key as the array index. </p> <pre><code>$sql = "SELECT category_id, category_name FROM Categories"; $result = mysql_query($sql); $arrCategories = array(); while ( $row = mysql_fetch_assoc($result) { $arrCategories[$row['category_id']] = $row['category_name']; } </code></pre> <p>Now, you have the names of all the categories in an array. </p> <p>When you're selecting articles, you'll have to do a separate query that pulls its category_ids from the join table. You can use a two-dimensional array to have a list of article ids and their associated categories</p> <pre><code>$arrArticleCategoryIds = array(); $result = mysql_query("SELECT * FROM articles, article_categories WHERE articles.article_id = article_categories.article_id AND articles.article_id = 1"); while ( $rows = mysql_fetch_array($result) ) { // why bother doing this when you've already hard-coded "1"? $article_id = $rows['article_id']; $article_title = $rows['article_title']; //(loop all the category_id from the 2nd table and add to the array below) // $categories_id[] .= ??????? --&gt; How do i do this? // here's how: $sql = "SELECT category_id FROM `article_categories` WHERE article_id = $article_id "; $category_id_results = mysql_query($sql); while ( $category_id_row = mysql_fetch_assoc($category_id_results) ) { $arrArticleCategoryIds[$article_id][] = $row['category_id']; } } </code></pre> <p>You'll wind up with two arrays:</p> <pre><code>$arrCategories Array ( [1] =&gt; apple [2] =&gt; banana ... ) $arrArticleCategoryIds Array ( [1] =&gt; Array ( [1] =&gt; 13 [2] =&gt; 9 ) [3] =&gt; Array ( [1] =&gt; 5 [2] =&gt; 7 ) ) ) </code></pre> <p>Where '1' and '3' are article ids, and 13, 9, 5, and 7 are category ids that belong to the article id they're found under. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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