简体   繁体   中英

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.

I need to insert data into a MySQL table from 2 tables and from a $_POST request.

I managed the info from the 2 tables that I needed, but I cannot seem to insert the $_POST variables.

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.

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?

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. Search them and follow the instructions.

Regarding using VALUES clause inside an INSERT INTO...SELECT statement: it doesn't work. Actually you would receive a "MySQL syntax error" message.

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.

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:

Note: The markers are legal only in certain places in SQL statements. 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. 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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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