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);
?>
Related Questions
- What role does proper data sanitization play in preventing syntax errors in SQL queries when updating database records in PHP, and how can it be implemented effectively?
- How can the key attribute be effectively used in Smarty foreach loops to count iterations and avoid conflicts with variable output?
- What potential pitfalls should be considered when sending form data via email using PHP?