39

Assuming that I have two tables, names and phones, and I want to insert data from some input to the tables, in one query. How can it be done?

Dharman
  • 30,962
  • 25
  • 85
  • 135
yossi
  • 3,090
  • 7
  • 45
  • 65

6 Answers6

69

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.

START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;

http://dev.mysql.com/doc/refman/5.1/en/commit.html

Lucio
  • 4,753
  • 3
  • 48
  • 77
Joshua Smith
  • 6,561
  • 1
  • 30
  • 28
  • 2
    Cheers Joshua, this helped me alot. Although in MySql I think this is START instead of BEGIN. – steve Oct 31 '12 at 16:07
  • 2
    What's the purpose of transactions? I gather that if something goes wrong in one of the queries in it then all queries will be rolled back. Is that it? Or is there also some gain in performance? – Clox May 11 '13 at 09:10
  • 3
    @Clox: That is partially the purpose of transactions. The other purpose is that the database will be in a known stable state before, during and after the transaction. This means that concurrent queries will never see partially committed data. – J.D. Pace Oct 21 '15 at 16:18
19

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
6

Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.

WITH names_inserted AS (
    INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
    INSERT INTO phones (id_name, phone) (
        SELECT names_inserted.id, '123-123-123' as phone
    ) RETURNING *
) SELECT * FROM names_inserted 
        LEFT JOIN phones_inserted 
            ON 
            phones_inserted.id_name=names_inserted.id

This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...

P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.

dmikam
  • 992
  • 1
  • 18
  • 27
3

I had the same problem. I solve it with a for loop.

Example:

If I want to write in 2 identical tables, using a loop

for x = 0 to 1

 if x = 0 then TableToWrite = "Table1"
 if x = 1 then TableToWrite = "Table2"
  Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT

either

ArrTable = ("Table1", "Table2")

for xArrTable = 0 to Ubound(ArrTable)
 Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT

If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

Oscar Zarrus
  • 790
  • 1
  • 9
  • 17
2

my way is simple...handle one query at time, procedural programming

works just perfect

//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
    //save second mysqli_query
    $insertQuery2 = "INSERT INTO users  (username, email, password) VALUES ('$username', '$email','$password')";
    $save2 = mysqli_query($conn, $insertQuery2);

    //check if second save is successfully
    if (isset($save2)){
        //save third mysqli_query
        $insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
        $save3 = mysqli_query($conn, $insertQuery3);

        //redirect if all insert queries are successful.
        header("location:login.php");
    }
}else{
    echo "Oopsy! An Error Occured.";
}

It's VIN
  • 152
  • 7
-1

Multiple SQL statements must be executed with the mysqli_multi_query() function.

Example (MySQLi Object-oriented):

    <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Obsidian
  • 3,719
  • 8
  • 17
  • 30
Shaju
  • 192
  • 1
  • 13
  • 1
    That's not a single query. You are just sending multiple queries at the same time to the server. There are still 2 inserts – Dharman Jul 09 '21 at 12:11