【发布时间】:2013-04-30 21:43:31
【问题描述】:
我正在创建一个电子商务商店,其中的 SQL 数据库设置了一个购物车。我设法让购物车工作并在数据库中设置了一些表。我现在在使用不同尺寸的产品时遇到问题,例如衬衫有 3 种不同的尺码,每种尺码也有不同的价格。
这是我的表格的设置方式:
CREATE TABLE products(
id int(11) NOT NULL auto_increment,
product_name varchar(255) NOT NULL,
price varchar(16) NOT NULL,
details text NOT NULL,
category varchar(16) NOT NULL,
subcategory varchar(16) NOT NULL,
date_added date NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY product_name (product_name)
)
CREATE TABLE admin(
id int(11) NOT NULL auto_increment,
username varchar(24) NOT NULL,
password varchar(24) NOT NULL,
last_log_date date NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY username (username)
)
CREATE TABLE sizes(
SizeID int(11) NOT NULL auto_increment,
id int(11) NOT NULL auto_increment,
Size varchar(24) NOT NULL,
Price varchar(6) NOT NULL,
PRIMARY KEY(sizeID),
UNIQUE KEY ID (ID)
)
我可以从产品表、名称、价格、类别等中获取信息,但我将如何从尺寸表和产品表中选择信息。此信息必须匹配,因此表必须由 FK 链接?
if(isset($_GET['id'])){
$id = preg_replace('#[^0-9]#i', '', $_GET["id"]);
//use this var to check to see if this ID exists, if yes then get the product
//details, if no then ecit this script and give message why
$sql=mysql_query("SELECT*FROM products WHERE id='$id' LIMIT 1");
$productCount=mysql_num_rows($sql);//count number of rows in sql variable
if($productCount>0){
//get all product details
while($row=mysql_fetch_array($sql)){
$id=$row["id"];
$product_name=$row["product_name"];
$price=$row["price"];
$details=$row["details"];
$category=$row["category"];
$subcategory=$row["subcategory"];
$date_added = strftime("%b %d %Y",strtotime($row["date_added"]));
//product_name, price, details, category, subcategory, date_added
}
}else{
echo "This item does not exist.";
exit();
}
}else{
echo "Data to render this page is missing.";
exit();
}
这会从产品表中获取数据,但我仍然需要尺寸表中的尺寸和价格,并且它们需要匹配商品 ID。我该怎么做呢?
【问题讨论】:
-
答案是肯定的。
-
我建议查看 PDO (php.net/manual/en/book.pdo.php) 并准备好声明,特别是为做一个电子商务网站。
-
一张表中不能有 2 个自增列。