INSERT and SELECT in single query MySQL

后端 未结 4 647
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题