Sort by category?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ofta
Forum Newbie
Posts: 3
Joined: Tue Apr 17, 2007 5:58 am

Sort by category?

Post by Ofta »

This shouldnt be a big problem you guys.

I need to know how to sort database objects after one specific field.

I have a field in the database thats named "cat" where all objects have a number.

So when the URL is: http://localhost/?cat=2 all the images thats displayed should be only the ones who have the number 2 saved in their "cat" field.

How do I do that?

Here is the code I use for display ALL the items.

Code: Select all

$query = "SELECT * FROM object ORDER BY pic DESC" or exit (mysql_error());
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

echo '<a href="#"><img src="'.$row['pic'].'.jpg" alt=" "></a>';

}
What do you have to add to that code so if there is a "?cat=X" at the end of the URL it should be checked and all the images that have the number X should be displayed?

I appreciate all answers! Thanks!
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

You need to modify your query and add in a WHERE clause. I would start out by searching the internet for SQL tutorials.
Ofta
Forum Newbie
Posts: 3
Joined: Tue Apr 17, 2007 5:58 am

Post by Ofta »

Begby wrote:You need to modify your query and add in a WHERE clause. I would start out by searching the internet for SQL tutorials.
Yeah I just got an answer from a post I did at another forum and this helped me:

Code: Select all

$query = "SELECT * FROM object WHERE cat=$_GET['cat'] ORDER BY pic DESC";
$result = mysql_query($query) or exit (mysql_error());;

while ($row = mysql_fetch_array($result)) {

echo '<a href="#"><img src="'.$row['pic'].'.jpg" alt=" "></a>';

}
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

8O

You're opening up a HUGE security hole by putting a _GET variable straight into an SQL statement. Use mysql_real_escape_string() to make it safe.
Post Reply