0

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;
4

2 回答 2

2

您错过了使用数据库的主要好处之一,那就是它非常擅长这类事情。

与其将所有产品加载到内存中,然后在 PHP 中执行您自己的搜索,不如使用 SQL 查询在数据库中搜索请求的产品,例如select * from products where id = :id.

于 2013-05-02T16:02:03.877 回答
0
Does this integer exceed the total number of products?

这并不总是正确的。一旦他们删除产品,这将不同步。

也就是说,更好的主意是将 id 转换为整数,并直接在 DB 上查询产品。不检查预加载的数组;这是没有意义的。

于 2013-05-02T16:03:27.410 回答