如何在mysql中同时插入和选择查询?

时间:2019-03-28 09:22:33

标签: mysql database

我有一个表名Blog,并使用下一个查询在表中插入数据

INSERT INTO `blog`(title,desc) VALUES ('blog1','description')

然后我通过使用

从表中选择数据
SELECT * FROM `blog`

这给数据库带来了两次成功。有没有可能同时执行两个查询的任何方法。我想一击数据库。

2 个答案:

答案 0 :(得分:1)

这是文件

https://www.php.net/manual/en/mysqli.quickstart.multiple-statement.php

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

答案 1 :(得分:0)

我想您可以使用以下语句:

  

插入blog(title,desc)值('blog1','description')SELECT *   FROM blog;