mysql - 从单个查询行中的两个表中检索值

时间:2016-06-13 17:40:00

标签: php mysql

我的问题对大多数人来说似乎很容易,但它有自己的曲折。我马上就会明白这一点。

我有一个PHP代码,它包含一个MySQL查询,其功能是从名为product_name的表中选择一个列products,然后再做一些事情。

以下是代码:

if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    foreach($_POST as $key => $value){ 
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
    }

    unset($new_product['type']);
    unset($new_product['return_url']); 


    $statement = $mysqli->prepare("SELECT product_name FROM products WHERE product_code=? LIMIT 1");
    $statement->bind_param('s', $new_product['product_code']);
    $statement->execute();
    $statement->bind_result($product_name);



    while($statement->fetch()){

        $new_product["product_name"] = $product_name; 

        if(isset($_SESSION["cart_products"])){  
            if(isset($_SESSION["cart_products"][$new_product['product_code']]))
            {
                unset($_SESSION["cart_products"][$new_product['product_code']]);
            }           
        }
        $_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item  
    } 
}

现在,我想要的是从两个表中检索数据,即productscat_1,两者都有完全相同的列名。显然,两个表中的数据都不同。但是,我也希望从cat_1检索相同的列,即product_name

我尝试过使用JOIN方法,但遇到了这个错误: Fatal error: Call to a member function bind_param() on boolean in D:\Work\offline\

那么,有没有办法做到这一点?任何解决方案都将不胜感激。

提前致谢。

2 个答案:

答案 0 :(得分:1)

你应该在这里使用join,但是,因为你在两个表中都有相同的列名,你必须给别名以使其有效:

$statement = $mysqli->prepare("
    SELECT 
           products.product_name AS p_product_name,
           cat_1.product_name AS c_product_name 
      FROM products
      JOIN cat_1
        ON --join clause here, maybe products.product_code = cat_1.product_code--
     WHERE products.product_code=? LIMIT 1");

....
$new_product["p_product_name"] = $p_product_name;
...

答案 1 :(得分:0)

是的,正确的方法是使用连接,但技巧是你想要什么样的连接。

根据您的描述,我们非常不清楚您正在尝试做什么,所以我会按照问题回答您的问题。此外,bindParam总是更好地使用命名变量(":pcode")。

$statement = $mysqli->prepare("
    SELECT products.product_name as name, cat_1.product_name as cat_name
    FROM products
    LEFT JOIN cat_1 ON products.product_code = cat_1.product_code
    WHERE products.product_code = :pcode
    LIMIT 1
");
$statement->bindValue(':pcode', $new_product['product_code']. PDO::PARAM_STR);
$statement->$execute();

不需要bind_result或循环,因为您限制为1个结果......

$product = $statement->fetchAll(PDO::FETCH_ASSOC);
echo $product ['name'] .':'. $product ['cat_name'] . '\n<br>';

...但是当你需要一个循环......

foreach ( $statement->fetchAll(PDO::FETCH_ASSOC) as $product ) {
    echo $product ['name'] .':'. $product ['cat_name'] . '\n<br>';
}