How can MySQL queries be properly integrated into a PHP script to insert email addresses from a file into a database table?
To properly integrate MySQL queries into a PHP script to insert email addresses from a file into a database table, you can use the fopen function to open the file, read each line to extract the email addresses, and then execute an INSERT query for each email address to insert them into the database table.
<?php
$filename = 'emails.txt';
$handle = fopen($filename, "r");
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$email = trim($line);
$query = "INSERT INTO emails (email) VALUES ('$email')";
$mysqli->query($query);
}
fclose($handle);
} else {
echo "Error opening the file.";
}
$mysqli->close();
?>
Related Questions
- What are some potential performance issues when running PHP scripts on a localhost server like XAMPP?
- What is the function nl2br() used for in PHP and how can it help with formatting text input?
- What are the best practices for ensuring proper variable scope and assignment within PHP class methods like constructors?