How can the INSERT SELECT syntax be used to improve efficiency in PHP?

Using the INSERT SELECT syntax in PHP can improve efficiency by allowing you to insert data into a table from the result set of a SELECT query in a single query, rather than executing separate INSERT and SELECT queries. This can reduce the number of queries sent to the database server, resulting in faster execution and improved performance.

<?php

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Using INSERT SELECT syntax to insert data from one table into another
$sql = "INSERT INTO table2 (column1, column2)
        SELECT column1, column2
        FROM table1
        WHERE condition";

if ($conn->query($sql) === TRUE) {
    echo "Data inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connection
$conn->close();

?>