2016-10-23 23 views
1

我創建了簡單的購物車應用程序。在這些我想添加產品到購物車中,從那個購物車我只選擇一個產品購買。我在使用id時感到困惑。任何人都可以幫我解決這個問題嗎?以spicific id顯示數據庫中的數據

這裏是添加到購物車中的代碼:

<?php  
Include('connect.php'); 

$productId=$_POST['productId']; 
$productName=$_POST['productName']; 
$productPrice=$_POST['productPrice']; 
$quantity=$_POST['quantity']; 

$sql=mysql_query("INSERT INTO products (productId,productName,productPrice,quantity) 
VALUES ('$productId','$productName','$productPrice','$quantity')") or  die(mysql_error()); 

if($sql){ 

$_GET['productId']=$productId; 
header('Location:buy.php'); 
} 
else 
{ 
echo"Failed to add cart !"; 

} 
?> 

這裏是獲取產品和顯示的代碼:

<?php 
include('connect.php'); 




$sql="SELECT productName FROM products WHERE productId=" . $productId . ""; 

$result = mysql_query($sql); 

$myArray = array(); 

echo "<table style='width:50%;'> 
<tr> 
<th>Product Name</th> 
<th>Product Price</th> 
<th>Quantity</th> 

</tr>"; 

$index = 0; 
while($row = mysql_fetch_assoc($result)) 
{ 
$myArray[$index] = $row; 
$index++; 

echo "<tr>"; 
echo "<td>" . $row['productName'] . "</td>"; 
echo "<td>" . $row['productPrice'] . "</td>"; 
echo "<td>" . $row['quantity'] . "</td>"; 
echo "</tr>"; 
} 

?> 
+0

從哪裏 「$的productId」 將在第二個代碼值? – jophab

回答

0

您需要使用mysql_insert_id()

例:

<?php 
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); 
if (!$link) { 
    die('Could not connect: ' . mysql_error()); 
} 
mysql_select_db('mydb'); 

mysql_query("INSERT INTO mytable (product) values ('kossu')"); 
printf("Last inserted record has id %d\n", mysql_insert_id()); 
?> 
0

您只能從產品表中選擇一列。但是您嘗試顯示$row['productPrice']$row['quantity'],您無法獲取此數據。

試試這個:

$sql="SELECT * FROM products WHERE productId='. $productId .'"; 

或者

$sql="SELECT productName, productPrice, quantity FROM products WHERE productId='. $productId .'"; 
+0

我嘗試但我收到錯誤,未定義索引 –

+0

檢查'$ result'你是否從查詢中使用此代碼獲取任何數據:'print_r($ result);退出;' –

+0

我dnt知道,但我使用的代碼,我收到未定義的索引錯誤,並警告:mysql_fetch_assoc()期望參數1是資源 –