How can PHP scripts be optimized for efficiency when transferring a large number of email addresses to a database?
When transferring a large number of email addresses to a database in PHP, it's important to optimize the script for efficiency to prevent performance issues. One way to do this is by using prepared statements to insert the data into the database, as it can help improve performance by reducing the overhead of repeatedly parsing and compiling SQL statements. Additionally, you can batch the inserts to reduce the number of queries sent to the database, further improving efficiency.
// Assume $emails is an array of email addresses to be inserted into the database
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");
// Prepare the insert statement
$stmt = $pdo->prepare("INSERT INTO emails (email) VALUES (:email)");
// Batch insert the email addresses
foreach (array_chunk($emails, 1000) as $chunk) {
$pdo->beginTransaction();
foreach ($chunk as $email) {
$stmt->execute(array(':email' => $email));
}
$pdo->commit();
}