我有一个代码,可以像这样在会话中添加一个数组:
array_push($_SESSION['cart']['1'] = 3);
array_push($_SESSION['cart']['18'] = 1);
这会添加项目ID" 1"数量" 3"并添加项目ID" 18"数量" 1"。我想在购物车页面上显示数据库中的这些项目。 我在php或sql中表现不佳,但有点像:
while (list ($id, $quantity) = each ($_SESSION['cart'])) {
$results = $conn->query("SELECT * FROM products ORDER BY id ASC");
}
并执行类似查找$id(from session) = $id(from database)
的操作,以便将会话显示为来自数据库的信息。使用项目名称,项目描述,项目价格和数量。
答案 0 :(得分:2)
以下是一个快速示例,重点介绍了您尝试从$ _SESSION中检索的内容(id_item):
http://www.tehplayground.com/#Iyf7c0LTM
$arr = array();
$arr['cart']['1'] = 3;
$arr['cart']['18'] = 5;
// This loop will display every id_item that had be added to the "cart"
foreach($arr['cart'] as $row)
{
print "id_item : " . $row . "\n";
}
你现在可以使用你的sql查询:
$sql = "SELECT * FROM products WHERE id =". $row;
编辑 - 由于您不清楚,我直接回答了问题:
<?php
session_start();
// Examples of shopped items (added to $_SESSION['cart'])
$_SESSION['cart']['1'] = 3;
$_SESSION['cart']['18'] = 5;
// This loop will display every id_item that had be added to the "cart"
// Further informations how foreach works with array
// https://stackoverflow.com/questions/10057671/how-foreach-actually-works
foreach($_SESSION['cart'] as $row)
{
print "id_item : " . $row . "\n";
}
// Full Display to help understanding the process
print "<pre>";
print_r($_SESSION['cart']);
print "</pre>";
?>
关于&#34; foreach如何与数组交互的高级解释&#34; :here
编辑2: 填充数据库变量+表的列名
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$mysqli = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Query the DB - Get itemID & quantity added in the cart table
$query = "SELECT itemID, itemQuantity FROM cart";
$result = $mysqli->query($query);
// Return the result into an array
$res_array = $result->fetch_array();
// Add the items into $_SESSION
// Pattern : $_SESSION['cart']['$itemId'] = $itemQuantity
foreach($res_array as $row)
$_SESSION['cart'][($row['itemID'])] = $row['itemQuantity']
print "<pre>";
print_r($_SESSION['cart']);
print "</pre>";
?>
示例:here
答案 1 :(得分:0)
不是从数据库中获取所有内容,然后在php中进行比较,您可以执行类似的操作,只获取所需的记录:
"SELECT * FROM products WHERE id IN(1,18) ORDER BY id ASC"
PHP可能就像:$in = implode(",", $_SESSION['cart']);
一样简单,尽管你也应该确保防止SQL注入。