[PHP/MYSQL] Output several fields not just 1

Discussion in 'PHP' started by boula2, Jul 26, 2008.

  1. #1
    Hello guys, could someone please help me with my question as i can't seem to find the answer myself. I have the following piece of code (see below) which basically displays a site name and the corresponding category. It only displays one category, but i would like it to display all the categories the site is corresponding with as there can be more then one. How would i do that?

    So to sum it up, basically $row['cname'] displays only 1 category next to the website, but i would like it to show all the categories the website is linked to.

    Thank you in advance for any help.

    Kind regards,

    boula

    part of script:
    
    <?
    
    		$query = "SELECT DISTINCT x.seo_code, z.name as cname, x.name, y.* FROM website x, website_category y, category z WHERE x.active = 1 AND x.id = y.website_id AND y.category_id=z.id ORDER BY RAND() DESC LIMIT 5";
    		$result = mysql_query($query);
    
    while ($row = mysql_fetch_assoc($result)) {
    	echo "<table width=\"775\" cellspacing=\"0\" bgcolor=\"#7eb8f2\" align=\"center\"><tr><td>
    <table width=\"773\" align=\"center\" cellspacing=\"5\" bgcolor=\"#c1e2f4\"><tr><td align=\"left\">
    					<font color=\"#7eb8f2\" face=\"Verdana\" size=\"4\">";
    	echo "<a href=\"http://www.bananapiewithmustard.com/" . $row['seo_code'] . "\"><b>" . $row['name'] . "</b></a>";
    	echo "</td><td align=\"right\"><font color=\"#3c96cb\" face=\"Verdana\" size=\"2\"><b>" . $row['cname'] . "</b></font>&nbsp;&nbsp;</td></tr></table>";
    	echo "</td></tr></table>";
    
    }
    
    ?>
    
    Code (markup):
    Database structure:

    
    website
    | id
    | name
    | active
    | seo_code
    
    website_category
    | website_id
    | category_id
    
    category
    | id
    | name
    
    Code (markup):
     
    boula2, Jul 26, 2008 IP
  2. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You query returns just one category. Remove the z (category) table from the query and make another query like:

    $category_result = mysql_query("SELECT name FROM category WHERE id = $category_id"); //where $category_id is from the result from website_category table.
    while($category = pg_fetch_row($category_result))
    {
      $categories .= $category[0].", "; //add a delimeter ", " to the string, to show the categories separated with commas
    }
    $categories = substr($categories, 0, -2); //remove the last delimeter
    PHP:

    Then, when drawing the table, use $categories instead of $row['cname'];
     
    xlcho, Jul 27, 2008 IP