I have this loop at the moment, but it involves calling the database 5 to 10 times. Is there a way I can just call it once, perhaps with a while loop, or any other alternatives anyone can think of, as it is slowing down the action.
foreach($_SESSION['cart_array'] as $each_item) {
$item_id = $each_item['item_id'];
$each_quantity = $each_item['quantity'];
$item_qry = mysql_query("SELECT * FROM `products` WHERE `products_id`=$item_id");
$item_row = mysql_fetch_assoc($item_qry);
$product_price = $item_row['products_price'];
$total_price += $product_price * $each_quantity;
}
yes, you could just select all the rows at once:
$total_price = 0;
if (!empty($_SESSION["cart_array"])) {
$query = "SELECT `products_price`, `products_id` FROM `products` WHERE `products_id` IN (";
$query .= implode(", ", array_map(function ($item) { return $item["item_id"]; }, $_SESSION['cart_array']));
$query .= ")";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
$items[$row["products_id"]] = $row["products_price"];
foreach ($_SESSION["cart_array"] as $item)
$total_price += $item["quantity"] * $items[$item["item_id"]];
}
One query solution:
$item_id_array = array();
$item_to_quant = array();
foreach($_SESSION['cart_array'] as $each_item)
{
$item_id_array[] = $each_item['item_id'];
$item_to_quant[$each_item['item_id']] = $each_item['quantity'];
}
$item_qry = mysql_query("SELECT * FROM `products` WHERE `products_id` IN (" . implode(',', $item_id_array) . ")");
$total_price = 0;
$results = array();
while ($item_row = mysql_fetch_assoc($item_qry))
{
//add total price to result array
$item_row['total_items_price'] = $item_row['products_price'] * $item_to_quant[$item_row['products_id']];
$results[] = $item_row;
$total_price += $item_row['total_item_price'];
}
You get results array and total price var as results.