我正在尝试做什么:
从数据库中提取数据并将其插入数组
我正在使用的代码:
sql = "SELECT * FROM `products`, categories WHERE category = cat_ID AND pro_ID = " . $_GET['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$name = $row['pro_name'];
$cartContents[$name] = array(
"id" => $row['pro_ID'],
"name" => $row['pro_name'],
"price" => $row['price'],
"quantity" => $_GET['q']
);
}
问题:
这确实从数据库获取值并将它们插入到数组中,但它会替换此前数组中的所有数据。
我尝试了什么:
- 用array(...)
替换[...]
- 使用以下代码:
$cartContents[$name]["id"] = $row['pro_ID'];
$cartContents[$name]["name"] = $row['pro_name'];
$cartContents[$name]["price"] = $row['price'];
$cartContents[$name]["quantity"] = $_GET['q'];
非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
如果您不希望为$cartContents[$name]
替换数据,只需更新您的代码;
$cartContents[$name][] = array(
"id" => $row['pro_ID'],
"name" => $row['pro_name'],
"price" => $row['price'],
"quantity" => $_GET['q']
);