MySQL and PHP query help
So here is my problem, I am creating categories for my website; however, I don't want all the categories to show up under my left nav bar, just a few select ones. Is there a way I could change this code to pick certain category ids, say 30 , 31, 33, and 35 to only show up? Your help is greatly appreciated!
<?php
// get categories
$sql = mysql_query("select * from categories where id != 1");
$count = mysql_num_rows($sql);
if($count > 0){
while($row = mysql_fetch_assoc($sql)){
$name = $row['name'];
print '<a href="c.php/'.$name.'/" style="margin-top: 2px; font-size: 12px; font-family: verdana">'.$name.'</a><br />';
}
}
else{
print 'There are currently 0 categories. Please login to your admin panel to manage categories.';
}
?>
Greg K posted this at 17:08 — 15th February 2008.
He has: 2,145 posts
Joined: Nov 2003
SELECT * FROM `categories` WHERE `id` IN(30,31,33,35);
'And to elaborate more to be easier to change:
<?
$goodCats = array(30,31,33,35);
$sql = "SELECT * FROM `categories` WHERE `id` IN(" . implode(',',$goodCats) . ")";
// get categories
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count > 0){
while($row = mysql_fetch_assoc($result)){
$name = $row['name'];
print ''.$name.'';
}
} else {
print 'There are currently 0 categories. Please login to your admin panel to manage categories.';
}
?>
-Greg
greg posted this at 18:06 — 15th February 2008.
He has: 1,581 posts
Joined: Nov 2005
Another option is if you have a descriptive column in the DB, such as product_name, you might benefit from using those instead of id numbers.
That way when you are looking at your code it is more clear what you are selecting from the database, rather than remembering what id numbers are for what product or having to view the DB
i.e. SELECT * WHERE product_name = books, dvd's
You can use pretty much anything in the query select to get from the DB. Just make sure you are selecting something that is unique, because it will list everything it finds for the criteria you tell it (unless you know you will be listing dupe results for a specific reason)
It all depends on what information you are wanting to show. You might want to display your 10 cheapest product prices. Or the first ten members who joined your site. The possibilities are (almost) endless.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.