简体   繁体   English

使用INSERT INTO SELECT和VALUES MYSQL PDO

[英]Using INSERT INTO SELECT and VALUES MYSQL PDO

After a lot of googling and running around the different questions in StackOverflow, I haven't really found a solution that solves my problem. 经过大量的搜索并在StackOverflow中解决了不同的问题之后,我还没有真正找到能够解决我的问题的解决方案。

I need to insert data into a MySQL table from 2 tables and from a $_POST request. 我需要将数据从2个表和$ _POST请求插入到MySQL表中。

I managed the info from the 2 tables that I needed, but I cannot seem to insert the $_POST variables. 我从所需的2个表中管理信息,但似乎无法插入$ _POST变量。

Here is what I have right now 这是我现在所拥有的

$stmt = $conn->prepare("INSERT INTO user_orders (order_item_id, order_item, order_quantity, order_user, order_name, order_address, order_phone) SELECT item_ID, item_name, item_quantity, user_name FROM $user_cart, user_main WHERE item_status = 'carted' and user_name = :user_name VALUES ($order_name, $order_address, $order_phone)");
$stmt->bindParam(":user_name", $_SESSION['login_user']);
$stmt->execute();

The server doesn't throw an error, it executes properly but no data is inserted. 服务器不会引发错误,它可以正确执行,但是不会插入任何数据。

The logic I'm following is that it's looking for more data after the SELECT statement to insert into the table for the open columns but it doesn't pick up the VALUES presented to it, probably due to bad syntax on my end. 我遵循的逻辑是,它正在SELECT语句后查找更多数据以插入到表中以打开的列中,但是它没有选择呈现给它的VALUES,这可能是由于我的语法错误所致。

QUESTION: What would be the proper way to insert the required data from 2 tables and from the $_POST request using 1 prepared PDO statement? 问题:使用1条准备好的PDO语句从2个表和$ _POST请求中插入所需数据的正确方法是什么?

You said: 你说:

The server doesn't throw an error, it executes properly but no data is inserted. 服务器不会引发错误,它可以正确执行,但是不会插入任何数据。

How did you conclude this? 您是如何得出结论的? Without error reporting and exception handling you can't be sure. 没有错误报告和异常处理,您将无法确定。

In my code are two TODO comments. 在我的代码中有两个TODO注释。 Search them and follow the instructions. 搜索它们并按照说明进行操作。

Regarding using VALUES clause inside an INSERT INTO...SELECT statement: it doesn't work. 关于在INSERT INTO...SELECT语句中使用VALUES子句:它不起作用。 Actually you would receive a "MySQL syntax error" message. 实际上,您会收到“ MySQL语法错误”消息。

You have to include the PHP values, eg the PHP variables $order_name , $order_address and $order_phone , as column identifiers in the SELECT part. 您必须将PHP值(例如PHP变量$order_name$order_address$order_phone )作为列标识符包含在SELECT部分中。

About the parameter markers used in an sql statement, this is what php.net says on the mysqli::prepare page about them - php.net doesn't specify this on the PDO::prepare page too, and I don't know why not: 关于sql语句中使用的参数标记,这就是php.netmysqli :: prepare页面上关于它们的内容-php.net也没有在PDO :: prepare页面上指定此参数,我也不知道为什么不:

Note: The markers are legal only in certain places in SQL statements. 注意:标记仅在SQL语句中的某些位置合法。 For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. 例如,在INSERT语句的VALUES()列表中(允许为一行指定列值),或者在与WHERE子句中的列进行比较以指定比较值时,允许使用它们。 However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. 但是,不允许在标识符(例如表名或列名),选择列表中使用标识符(由SELECT语句返回)或指定二进制运算符的两个操作数(例如=等号)时使用标识符。

At last, the code: 最后,代码:

<?php

/*
 * ============================================================
 * Set error reporting level and display errors on screen.
 * Use it ONLY ON A DEVELOPMENT SYSTEM, NEVER ON PRODUCTION!
 * If you activate it on a live system, then the users will see
 * all the errors of your system. And you don't want this!
 * ============================================================
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // Read needed variables.
    // TODO: Provide your values.
    $user_cart_table_name = 'user_cart_table_name';
    $user_name = 'user name value';
    $order_name = 'order name value';
    $order_address = 'order address value';
    $order_phone = 'order phone value';

    // Create a PDO instance as db connection.
    // TODO: Delete this and use your own connection. 
    //       But use the first two driver options that I defined here as
    //       the options on your connection.
    $conn = new PDO(
            'mysql:host=localhost;port=3306;dbname=mydb;charset=utf8'
            , 'myuser'
            , 'mypass'
            , array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => FALSE,
        PDO::ATTR_PERSISTENT => TRUE,
            )
    );

    /*
     * The sql statement - it will be prepared.
     * 
     * Familiarize yourself with the sprintf() function.
     * It is your very good friend when building complex
     * sql statements.
     */
    $sql = sprintf('INSERT INTO user_orders (
                        order_item_id,
                        order_item,
                        order_quantity,
                        order_user,
                        order_name,
                        order_address,
                        order_phone
                    ) 
                    SELECT 
                        item_ID,
                        item_name,
                        item_quantity,
                        user_name,
                        "%s",
                        "%s",
                        "%s" 
                    FROM 
                        %s,
                        user_main 
                    WHERE 
                        item_status = "carted" 
                        AND user_name = :user_name'
            , $order_name
            , $order_address
            , $order_phone
            , $user_cart_table_name
    );

    // Prepare the sql statement.
    $stmt = $conn->prepare($sql);

    // Bind the input parameters to the prepared statement.
    $bound = $stmt->bindValue(':user_name', $user_name, PDO::PARAM_STR);

    // Execute the prepared statement.
    $executed = $stmt->execute();

    // Get the last insert id.
    $lastInsertId = $conn->lastInsertId();

    // Display last insert id.
    echo 'Record added with id ' . $lastInsertId;

    // Close connection.
    $conn = NULL;
} catch (PDOException $exc) {
    echo $exc->getMessage();
    exit();
} catch (Exception $exc) {
    echo $exc->getMessage();
    exit();
}

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM