0

嗨,我正在尝试echo使用产品的名称,Product Table但取而代之的是它echo的名称Category table。除了更改两张表之一的名称之外,它们是否是一种阻止这种情况的方法?

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"];
4

3 回答 3

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"];
于 2013-06-21T22:54:46.757 回答
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);

请注意,您需要使用 the:而不是 the$并且您不需要引用变量。

于 2013-06-21T22:58:14.643 回答
0

当您获取值时,PHP 不使用该表来限定名称。它将使用最后一个值,因此Name将引用类别名称。您可以颠倒您选择Product/Category名称的顺序,但使用别名更有意义。

SELECT Product.Name AS proName, Category.Name AS catName

$product_name = $row['proName'];
于 2013-06-21T22:54:36.657 回答