Insert into multiple tables in one query

Viewed 124679

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?

6 Answers

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.

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.";
}

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