How can the repetitive database connection and insertion process be optimized in the code snippet?

The repetitive database connection and insertion process can be optimized by creating a reusable function that handles the database connection and insertion. This function can accept parameters such as the SQL query and data to be inserted, making the code more modular and efficient.

<?php

// Function to handle database connection and insertion
function insertData($data) {
    $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);
    }

    // Prepare and bind the SQL query
    $stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
    $stmt->bind_param("ss", $data['value1'], $data['value2']);

    // Execute the query
    $stmt->execute();

    // Close statement and connection
    $stmt->close();
    $conn->close();
}

// Example of calling the function with data to be inserted
$data = array('value1' => 'example1', 'value2' => 'example2');
insertData($data);

?>