INSERT and SELECT in single query MySQL

后端 未结 4 641
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 07:02

How can I do one single query with both an INSERT and SELECT in it and then read the results of selection? I want to insert and then select something, all must be d

相关标签:
4条回答
  • 2020-12-20 07:15

    Not possible, and wouldnt recommend doing it either, as kappa points out, if you perform 2 seperate queries you'll be able to check for results etc. which is preferable.

    0 讨论(0)
  • 2020-12-20 07:18

    I wouldn't recommend this either but you can use pdo to do this as shown in this thread: PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

    0 讨论(0)
  • 2020-12-20 07:19

    all must be done in one query...

    Why do you need to do everything in one query ?

    Like Wiseguy said, I think what you are looking for is called a transaction.

    Also, It might be a good idea considering updating to PDO, which will give you a more complete toolset like transactions and query parameters.

    Anyway, for answering your initial question, no it is not possible.

    Update: Here is an example of a transaction in PDO.

    try
    {
        $pdo->beginTransaction();
    
        $pdo->query(' ... ');
        $pdo->query(' ... ');
        $pdo->query(' ... ');
    
        $pdo->commit();
    }
    catch(Exception $e)
    {
        $pdo->rollback();
        die($e->getCode() . ': ' . $e->getMessage());
    }
    
    0 讨论(0)
  • 2020-12-20 07:37

    It is possible to send multiple statements in PHP if you are using the mysqli extension, which is a good idea to use instead of the older mysql extension for a lot of reasons. Here is a modified example from the multiple statements section of the documentation, based on your question:

    $mysqli = new mysqli("example.com", "user", "password", "database");
    
    $sql .= "INSERT INTO table1 (field1,field2) VALUES('aaa','bbbb') ON DUPLICATE KEY UPDATE `field1` = 'cccc', `field2`='ffffdffffd';";
    $sql .= "SELECT field3 Form Table3 WHERE field3='eeeee';";
    
    $mysqli->multi_query($sql);
    
    do {
        if ($res = $mysqli->store_result()) {
            var_dump($res->fetch_all(MYSQLI_ASSOC));
            $res->free();
        }
    } while ($mysqli->more_results() && $mysqli->next_result());
    ?>
    

    Notice that the documentation does dedicate airtime to security risks of multiple statements, which everyone is pointing out. The other reason, of course, that it's not always a great idea is if you want the second statement to be affected by the first statement.

    0 讨论(0)
提交回复
热议问题