将存储在会话存储中的数据插入MongoDB

时间:2018-04-07 12:11:09

标签: php mongodb

我无法将存储在会话存储中的数据插入MongoDB。我已经创建了一个数组来将数据显示到我的HTML表格中,但我无法将其插入到MongoDB中。

<?php
//Extract the product IDs that were sent to the server
$prodIDs= $_POST['prodIDs'];

//Convert JSON string to PHP array 
$productArray = json_decode($prodIDs, true);

echo '<table id="basket_list">';
echo '<tr><th>Product Image</th><th>Product Name</th><th>Price</th><th>Count</th></tr>';
for($i=0; $i<count($productArray); $i++) {
    echo '<tr>';
    echo '<td class="image_column"><img class="basket_img" src="' . $productArray[$i]['image'] . '"></td>';
    echo '<td>' . $productArray[$i]['name'] . '</td>';
    echo '<td class="totalPrice">£' . $productArray[$i]['price'] . '</td>';
    echo '<td>' . $productArray[$i]['count'] . '</td>';
    echo '</tr>';
}
echo '</table>';

$mongoClient = new MongoClient();

$db = $mongoClient->ecommerce;

$collection = $db->orders;

//Convert to PHP array
$orderData = [
    "image" => $productArray["image"],  
    "name" => $productArray["name"], 
    "price" => $productArray["price"], 
    "count" => 1
];

//Add the order to the database
$returnVal = $collection->insert($orderData);

//Close the connection
$mongoClient->close();
?>

1 个答案:

答案 0 :(得分:1)

$productArray是多维的,因此您需要像$productArray[<index>]["<attribute>"]一样访问它。插入数据时也可以循环它。

$mongoClient = new MongoClient();
$db = $mongoClient->ecommerce;
$collection = $db->orders;

for($i=0; $i<count($productArray); $i++) {

    //Convert to PHP array
    $orderData = [
        "image" => $productArray[i]["image"],  
        "name" => $productArray[i]["name"], 
        "price" => $productArray[i]["price"], 
        "count" => 1
    ];

    //Add the order to the database
    $returnVal = $collection->insert($orderData);

}

//Close the connection
$mongoClient->close();

或仅访问第一个(或任何其他)单个元素。

$orderData = [
    "image" => $productArray[0]["image"],  
    "name" => $productArray[0]["name"], 
    "price" => $productArray[0]["price"], 
    "count" => 1
];