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:
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;
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
.