【问题标题】:Unable to Insert Select statement with php mysql prepared statement无法使用 php mysql 准备好的语句插入 Select 语句
【发布时间】:2015-11-08 02:18:57
【问题描述】:

谁能帮我查询mysql。我正在尝试使用插入选择语句插入多行。

if ($insert_stmt = $mysqli->prepare("INSERT INTO order_processing_info (order_id, cart_item_id, item_id, price, quantity) VALUES (?, (SELECT s.cart_item_id, i.item_id, i.price, s.quantity FROM inventory_info AS i, cart_info AS s  WHERE i.item_id=s.item_id AND s.user_id = ?))")) {
                    $insert_stmt->bind_param('ss', $order_id, $user_id);

我认为问题是因为我希望这里所有插入的 order_id 都相同,尽管我不确定。

之前我尝试在 select 语句块中运行它,但没有成功。

if ($select_stmt = $mysqli->prepare("SELECT i.item_id, i.price, s.quantity, s.cart_item_id FROM inventory_info AS i, shopping_cart_info AS s  WHERE i.item_id=s.item_id AND s.user_id = ?")) {
        $select_stmt->bind_param("s", $user_id);
        $select_stmt->execute();
        $select_stmt->bind_result($item_id, $price, $quantity, $cart_item_id);

        while ($select_stmt->fetch()) {

            if ($insert_stmt = $mysqli->prepare("INSERT INTO order_processing_info (order_id, cart_item_id, item_id, price, quantity) VALUES (?, ?, ?, ?, ?)")) {
                $insert_stmt->bind_param('sssss', $order_id, $cart_item_id, $item_id, $price, $quantity);
                // Execute the prepared query.
                if (!$insert_stmt->execute()) {
                    header('Location: ../error.php?err=INSERT failure: INSERT');
                    exit();
                }
            }
        }
        $select_stmt->close();
    }

我在stackoverflow上查了很多,但我想我对数据库查询不是很精通,所以如果有人能帮助我,我将不胜感激。

【问题讨论】:

    标签: php mysqli prepared-statement insert-select


    【解决方案1】:

    使用“INSERT INTO SELECT”查询(http://www.w3schools.com/sql/sql_insert_into_select.asp),此时只需绑定一个参数,即用户 ID。它还可以节省循环中查询的开销

    【讨论】:

    • 感谢我能够通过将插入语句放入选择语句获取结果的循环中来解决它。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多