【发布时间】:2014-03-15 16:28:53
【问题描述】:
我有带购物车的小页面。一切都是在会话中存储。现在我需要将这些数据保存到 mysql 数据库中。
我认为,我需要使用 foreach 循环来执行此操作,但我无法构造它。有人知道解决方案吗?
这是显示购物车的功能。
function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$total=0;
$output[] = '<table>';
foreach ($contents as $id_menu=>$qty) {
$sql = 'SELECT * FROM menu WHERE id_menu = '.$id_menu;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id_menu='.$id_menu.'" class="r">Delete</a></td>';
$output[] = '<td>' .$name. '</td>';
$output[] = '<td>' .$price.' Kč</td>';
$output[] = '<td><input type="text" name="qty'.$id_menu.'" value="'.$qty.'" size="5" maxlength="5" /></td>';
$output[] = '<td>' .($price * $qty).' Kč</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Total: <strong>'.$total.' EUR</strong></p>';
$output[] = '<div><button type="submit">Update</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Cart is empty.</p>';
}
return join('',$output);
}
【问题讨论】:
-
您到底想在数据库中存储什么? $name $price $qty $total ???还是别的什么????
-
你是对的,它可能是一个循环,用于保存要插入的项目的任何变量。所以首先看一下将要插入的数据的存储位置和方式。然后转到 SO 上关于在 MySQL 中插入多行的现有问题之一,例如 this one,如果您仍有问题,请使用 relevant 代码提出更具体的问题。
-
@CyberBoy 是的,$name $price $qty
标签: php mysql database session