Would this be sufficient validation of a product ID in php?

I'm working on a very small webshop with a very limited number of projects using codeigniter.

At the start of the script, the products model gets the entire list of products and stores the result as an array as a property of this model.

The product ID's are simply the auto incremented primary keys from the database. So when somebody adds a product to the cart the ID gets sent with POST. I then check three things:

  • Could $id be an integer?
  • Does this integer exceed the total number of products?
  • Does this integer match a product ID?

Basically -although slightly simplified- I do this:

// Count total number of items
$total = count($this->productArray)

if (!(int)$id || $id > $total)
    return false;

foreach($this->productArray as $product) {
    if ($product['id'] == $id)
        return true;
}

return false;

Answers


Does this integer exceed the total number of products?

This will not always be true. As soon as they delete products this will get out of sync.

That said the better idea would be to cast the id to an integer, and the query for the product directly on the DB. Not check against a preloaded array; That makes no sense.


You're missing one of the main benefits of using a database, which is that it is very good at exactly this sort of thing.

Instead of loading all the products into memory, and then performing your own search in PHP, you should search for the requested product in the database using an SQL query like select * from products where id = :id.


Need Your Help

PSQLException: ERROR: syntax error in tsquery

postgresql search full-text-search escaping

Which characters must be avoided to make sure PSQLException: ERROR: syntax error in tsquery will not occur?

Adding a path for a ImageIcon - Java

java variables reference imageicon

Hey So I'm pretty much awful at java and I want to add a ImageIcon now I've done this before and I even have the images to work the only issue is the program I am making is for University work and ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.