0

I have a cart class, where I store the product ids. The user can open the cart through a button that opens the cart in a popup, so the cart content has to be loaded in every page.

I can store only the ids of the products because of the size limits, but I want to show the product names to the final user, so for each element I need to make a query and get the product data from the database.

Is there any major drawback by doing this? Or are there better solutions?

PS: I could get the id of all the products in the cart, and then do one single query that gets the data of any needed product. I’d rather avoid this since I would need to rewrite parts of the class, so is there any actual difference with the previous solution?

PPS: The total number of sql queries shouldn’t be too high in any case. Of course I wouldn’t mind, but I strongly doubt any user will purchase hundreds of different products at one time.

4

1 回答 1

2

我只想从你的问题中强调一句话:

所以对于每个元素,我需要进行查询并从数据库中获取产品数据。

那是你的问题。你不需要这样做。您可以使用单个查询来查询您的数据库,并询问 ID 列表中的所有产品。

SQL 语言的一个有用部分是IN(....)子句。

$ids = [123, 884, 7848, 2882, 3232]; // let's say that is your input
$idList = implode(',', array_map('intval', $ids));
$sql = sprintf(
    "SELECT field1, field2, field3 FROM products WHERE products.ID IN(%s)",
    $idList
);

这是对产品 ID 列表的单个查询。当您从数据库中获取数据时,您会动态创建一个内存数据库(也称为Hashtable),以便您可以根据 ID “获取”数据:

foreach($ids as $id)
{
    $concreteProduct = $rows[$id];
    ...
}

您也知道它array,只是由从数据库返回的 ID 值作为键。由于 ID 是唯一的,因此仅适用于tm

希望这会有所帮助。有些人可能称之为过早优化,但是,您应该了解这个概念,因为这可以在许多情况下使用。

于 2012-09-21T20:15:40.013 回答