user11271073
user11271073

Reputation:

How to insert and select query at the same time in mysql?

I have one table name Blog and i insert data on the table by using tne next query

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

And then i select data from the table by using

SELECT * FROM `blog`

This gives two hit to the database. Is there any possible way to do both queries at the same time. I want to make the process with one hit to the database.

Upvotes: 1

Views: 5032

Answers (2)

GANESH A S
GANESH A S

Reputation: 41

i suppose you can use below statement :

INSERT INTO blog(title,desc) VALUES ('blog1','description') SELECT * FROM blog ;

Upvotes: 1

Vinh Can Code
Vinh Can Code

Reputation: 427

Here is the document

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());
?>

Upvotes: 1

Related Questions