2013-05-02 51 views
0

我正在做我的功課。我有一個購物車會話,我可以基於產品ID獲取mySql數據庫中的屬性。無法從購物車會話中獲取ID

<?php 
$total_price=0; 
if(isset($_SESSION['cart']) ? $_SESSION['cart'] : null) 
{ 
echo "<tr> 
    <th></th> 
    <th>Product</th> 
    <th>Price</th> 
    <th>Quantity</th> 
    </tr>"; 
foreach ($_SESSION['cart'] as $key => $product) { 
    $the_query = "SELECT * FROM products WHERE id=" . $product->id; 
    $the_product = $db->query($the_query) or die('Query failed: '.mysql_error()); 
     $the_product->execute(); 
     $the_product->setFetchMode(PDO::FETCH_OBJ); 

     while ($row = $the_product->fetch()){ 
     $total_price = $total_price + $row->price*$product->quantity; 
     echo "<tr><td>"; 
     echo "<img src='".$row->image_url_small."' /></a></td>"; 
     echo "<td><strong>".$row->name."</strong></td><td><em>$".$row->price."</em>"; 
     echo '</td>'; 
     echo '<td><input type="text" id="'.$row->id.'" class="override" value="'.$product->quantity.'"/></td>'; 
     echo '<td><a href="do_deletecart.php?id="'.$row->id.'">Delete item </a></td></tr>'; 
    }} 

    echo "<tr><td colspan='2'></td></tr>"; 
    echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>"; 

} 
else { 
echo "Your cart is empty."; 
} 
?> 

更新 我可以通過ID來do_deletecart.php。但現在我可以從車 刪除產品do_deletecart.php

<?php 
session_start(); 

$product = $_GET['id']; 

foreach($_SESSION['cart'] as $key=>$value) { 

if($product == $value) 
{ 
    unset($_SESSION['cart'][$key]); 
     break; 

} } 

header("location:cart.php");  

?> 
+0

你在你的文件的頂部開始會話之前 session_start();? – 2013-05-02 10:56:20

+0

是的,我做過。我可以得到除了ID – user2210209 2013-05-02 10:58:01

回答

1

好吧,假設$row->id包含你的期望,你有引號,這將從根本上終止<a>元素的href屬性包圍它。

您需要按照以下步驟更新您的代碼:

echo '<td><a href="do_deletecart.php?id='.$row->id.'">Delete item </a></td></tr>'; 

而且,你可能要檢查你其實已經開始了會議。爲了訪問超全局的$_SESSION,在將任何輸出發送到瀏覽器之前,您需要先調用session_start()

+0

以外的所有其他值,謝謝,先生。這需要我幾個小時,但只有1秒鐘。 – user2210209 2013-05-02 11:10:36

+0

沒問題。如果有幫助,您可能會喜歡接受該答案。 – BenM 2013-05-02 11:14:16

0

你需要確保你包括使用$ _SESSION