Page 1 of 1

Sort by category?

Posted: Tue Apr 17, 2007 6:00 am
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!

Posted: Tue Apr 17, 2007 7:07 am
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.

Posted: Tue Apr 17, 2007 8:16 am
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>';

}

Posted: Tue Apr 17, 2007 8:32 am
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.