[PHP] Validation Problem

They have: 4 posts

Joined: Jan 2003

Hi, I just signed up here and thought to have my first post as a problem solver Wink. I've posted this exact same problem on the sitepoint forums but saidly no one was able to answer what i had wanted.

Problem:
I am creating a computer website for customers and eager customers to see what products the company is currently selling. I have id's for everything. From category id's to product_id's.

Now I need to validate if the viewer is refered with a correct ID. I have a php page called "Showcat.php" which uses the ID for the category to list all products under it. But the company owner has reported to me that some people are misusing this and entering the wrong ID(eg, showcat.php?id=340).

I the showcat.php to check if the ID passed in the ID variable is correct or not. IF it is wrong, ouput a friendly error otherwise do query.

All help would be great.

He has: 1,016 posts

Joined: May 2002

I'm assuming you're using MySQL to store the products and categories...

<?php
$result
= mysql_query(\"SELECT id FROM categories WHERE id = '$id'\");
if(mysql_num_rows(
$result) < 1) {
    echo \"The category does not exist!\".
}
?>

They have: 4 posts

Joined: Jan 2003

Neverworked mate.

He has: 1,016 posts

Joined: May 2002

You need to edit it to fit your needs. Also you must be connected to the MySQL server before you execute the above code. If you do that correctly, then it should work (unless I've typed it wrong Laughing out loud).

nike_guy_man's picture

They have: 840 posts

Joined: Sep 2000

Looks like it'll work... as long as MySQL is installed and working
Are you getting any errors?
(Welcome to TWF too, Alkaif Khan)

They have: 4 posts

Joined: Jan 2003

I mean that works but not for what i need.

IT should check the ID against the list of ids there.

Say i have 7 ids in the ID column

ID
1
2
3
4
5
6
7

and showcat.php?id=39489 wants to show an id of 39489 but we dont have the ID 39489 so then it should output an error saying "hey this is not a valid ID." or something like that.

I know that can be done, but how?

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Alkaif Khan, the code Zollet provided should do the job. Post your code, and we'll make the appropriate changes for you.

He has: 1,016 posts

Joined: May 2002

Alkaif, the code I posted checks the database for that ID, if it's not there, will not result any lines which then prints the category does not exist.

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.