您好我正在尝试echo
来自Product Table
的{{1}}产品名称,而是echo
来自Category table
的名称。
除了从2个表中的一个更改名称之外,它们是否可以阻止它?
Table: Product
Pid Name
1 man
2 woman
3 child
Table: Category
CatID Name Pid
1 pen 1
2 pen 1
3 pencil 2
3 red_pen 3
Table: active_product
ATpid size pid price
1 12 1 10
2 14 2 15
3 16 3 20
4 18 4 30
PDO:
$stmt = $conn->prepare("
SELECT Product.Name, Category.Name, size, Price
FROM active_Product, Product, Category
WHERE Product.ProdID ='$item_id'
AND size = '$size '
AND Category.Name = '$pcategory'
Limit 1");
$stmt->bindParam('$item_id',$item_id);
$stmt->bindParam('$size',$size);
$stmt->bindParam('$pcategory',$pcategory);
$stmt->execute();
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row ){
$product_name = $row["Name"];
答案 0 :(得分:1)
试试这个:
SELECT Product.Name AS PName, Category.Name AS CName, size, price
FROM active_product, Product, Category
WHERE Product.pid=1 AND size=10 AND Name.Category="pen" Limit 1
然后在PHP中,执行以下操作:
$product_name = $row["PName"];
所以你的最终产品应该是这样的:
$stmt = $conn->prepare("
SELECT Product.Name AS PName, Category.Name AS CName, size, Price
FROM active_Product, Product, Category
WHERE Product.ProdID ='$item_id'
AND size = '$size '
AND Category.Name = '$pcategory'
Limit 1");
...
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row ){
$product_name = $row["PName"];
答案 1 :(得分:0)
当您获取值时,PHP不会使用该表来限定名称。它将使用最后一个值,因此Name
将引用类别名称。您可以撤消选择Product
/ Category
名称的顺序,但使用别名更有意义。
SELECT Product.Name AS proName, Category.Name AS catName
$product_name = $row['proName'];
答案 2 :(得分:0)
除了已经提到的更正之外,你没有绑定任何变量,你只是在sql语句中注入它们。
您应该使用:
$stmt = $conn->prepare("
SELECT Product.Name as productName, Category.Name as categoryName, size, Price
FROM active_Product, Product, Category
WHERE Product.ProdID =:item_id
AND size = :size AND Category.Name = :pcategory Limit 1");
$stmt->bindParam(':item_id',$item_id);
$stmt->bindParam(':size',$size);
$stmt->bindParam(':pcategory',$pcategory);
而不是:
$stmt = $conn->prepare("
SELECT Product.Name, Category.Name, size, Price
FROM active_Product, Product, Category
WHERE Product.ProdID ='$item_id'
AND size = '$size ' AND Category.Name = '$pcategory' Limit 1");
$stmt->bindParam('$item_id',$item_id);
$stmt->bindParam('$size',$size);
$stmt->bindParam('$pcategory',$pcategory);
请注意,您需要使用:
而不是$
,并且不需要引用变量。