How can PHP scripts be organized to efficiently handle database insertion tasks?

To efficiently handle database insertion tasks in PHP scripts, it is recommended to separate database-related logic into separate functions or classes. This helps in organizing the code, improving readability, and making it easier to maintain and debug. By encapsulating database insertion tasks within dedicated functions or classes, it also promotes code reusability and reduces the risk of errors.

// Function to handle database insertion
function insertDataIntoDatabase($data) {
    // Connect to the database
    $conn = new mysqli("localhost", "username", "password", "database");

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

    // Prepare the SQL statement
    $sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    
    // Bind parameters and execute the statement
    $stmt->bind_param("sss", $data['value1'], $data['value2'], $data['value3']);
    $stmt->execute();

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

// Usage
$data = array(
    'value1' => 'data1',
    'value2' => 'data2',
    'value3' => 'data3'
);

insertDataIntoDatabase($data);