What is the recommended approach for inserting individual words from a text file into a table using PHP?
When inserting individual words from a text file into a table using PHP, you can read the file line by line, split each line into words, and then insert each word into the table. This can be achieved by using file handling functions in PHP, such as fopen and fgets, along with database functions like mysqli_query to insert the words into the table.
<?php
// Open the text file for reading
$filename = 'words.txt';
$file = fopen($filename, 'r');
// Connect to the database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// Loop through each line in the file
while (!feof($file)) {
$line = fgets($file);
$words = explode(' ', $line);
// Insert each word into the table
foreach ($words as $word) {
$word = trim($word);
$mysqli->query("INSERT INTO words_table (word) VALUES ('$word')");
}
}
// Close the file and database connection
fclose($file);
$mysqli->close();
?>