我正在根据我正在关注的教程创建一个链接到 SQL 数据库的 PHP 购物车。
下面的代码应该显示我所有的产品,但是我相信
$id = intval($_GET['id']);
部分搞砸了。产品的 SKU 是 Varchar,而不是整数,所以我相信这是导致“intval”问题的原因。我可以插入另一种数据类型来再次显示我的产品吗?
<?php
if (isset($_GET['action']) && $_GET['action'] == "add")
{
$id = intval($_GET['id']);
if(isset($_SESSION['cart'][$id]))
{
$_SESSION['cart'][$id]['quantity']++;
}
else
{
$sql2 = "SELECT * FROM products WHERE SKU={$id}";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) != 0)
{
$row2 = mysql_fetch_array($query2);
$_SESSION['cart'][$row2['SKU']] = array("quantity => 1, "price" => $row['price']);
}
else
{
$message = "This product id is invalid";
}
}
}
?>
<h2 class="message"><?php if(isset($message)){echo $message; ?></h2>
<h1>Product Page</h1>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql = "SELECT * FROM products ORDER BY SKU ASC";
$query = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_assoc($query))
{
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['Description']; ?></td>
<td><?php echo "£" . $row['price']; ?></td>
<td><a href="index.php?page=products&action=add&id=<?php echo $row['SKU']; ?>">Add to Cart</a></td>
</tr>
<?php
}
?>
</table>