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

Increase the size of Bootstrap 2.3's Glyphicons

javascript jquery css twitter-bootstrap

Is there an easy way of increasing the size of Glyphicons?

Java return int from Object via HashMap

java swing jtable

I have a question belonging Indexing. I have created a HashMap in a separate class, to get a database for a key and the coordinates of the key.