Re: switch and while
| From: | Chris | Date: | Mon, 07 Sep 2009 00:51:58 +0000 |
| Subject: | Re: switch and while | ||
| References: | 1 2 3 4 5 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-46473@lists.php.net to get a copy of this message | ||
Emiliano Boragina wrote:
Hi Chris, Sorry... you're right! With this I want to print the category in a html table after a search... The search find the data, and print category and description. This category is a number (ID), but I want to print the name of the category. My MYSQL CATEGORY TABLE have ID and NAME, so using the SWITCH, I want to put in CASE the ID and ECHO the NAME. In other webs I do switch($category) //where $category is an array fom the db { case 1: echo "category1"; break; case 2: echo "category2"; break; ... } I want the 1, 2, 3... like the ID from my table, and "category1, category2..." like the NAME from my table Do not know if it was understood...There are a couple of ways you can do it and no need for a switch. 1) get the category name as part of the query itself This works nicely if an article only fits into one category. If it fits into multiple categories, it gets a little messy (though it's still doable). <guessing tablenames etc> select * from articles where id='x'; becomes select a.*, c.category_name from articles a inner join categories c on (a.category_id=c.category_id) where id='x'; 2) load all categories at once and then print the relevant one This works if you have a small number of categories available. If you have a lot (50+) then I'd look at the first method. $category_list = array(); $category_query = "select * from categories order by category_name"; $category_result = mysql_query($category_query); while ($row = mysql_fetch_assoc($category_result)) { $cat_id = $row['category_id']; $cat_name = $row['category_name']; $category_list[$cat_id] = $cat_name; } then you can just print out the name, eg: // article_category comes from your query to load the article. $article_category = 'x'; // make sure it's a valid category name if (isset($category_list[$article_category])) { echo "Your article is in category " . htmlspecialchars($category_list[$article_category]); } -- Postgresql & php tutorials http://www.designmagick.com/