首页 > 解决方案 > 如何在 php 中准备 INSERT INTO SELECT 查询?

问题描述

我正在尝试将产品从购物车(来自 cart_product)复制到 order_product 表

通过准备列名成为 order_id 的值,这个查询可以这样工作吗

    // Create the order

    $order_id = $this->order->store();

    // Copy products from cart and assign them to the order

    $req = "INSERT INTO order_product (order_id, product_id)
    SELECT :order_id, product_id, 
    FROM cart_product, cart
    WHERE cart.user_id = :id";

    $bind = array(
        "id" => $_SESSION['id'],
        "order_id" => $order_id
    );

    return  $this->Sql($req);

我正在使用一个微框架,其中 Sql 函数来自。

我希望查询变成这样

INSERT INTO order_product (order_id, product_id)
SELECT 3, product_id, 
FROM cart_product, cart
WHERE cart.user_id = 2

标签: phpmysqlsqlprepared-statementinsert-into

解决方案


解决方案:问题是由 FROM 行末尾的逗号引起的。这就是导致问题的原因,而不是无法将列绑定为值。我没有错误消息,因为我使用的是微型专有框架。


推荐阅读