gpt4 book ai didi

php - 如何使用 session 数组从数据库选择中提取项目?

转载 作者:可可西里 更新时间:2023-11-01 08:29:37 26 4
gpt4 key购买 nike

我有这样的代码,可以将数组添加到 session 中:

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");
}

并执行类似 find $id(from session) = $id(from database) 这样我可以将 session 显示为来自数据库的信息。包含商品名称、商品描述、商品价格和数量。

最佳答案

这是一个简单的示例,突出显示了您尝试从 $_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>";

?>

关于“foreach 如何与数组交互”的高级解释: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

关于php - 如何使用 session 数组从数据库选择中提取项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com