Create a file-handle with fopen()
, check if its a valid handle, run a loop with fgets()
as the argument to the loop - this will have each line individually stored as a variable inside the loop, in this case $line
. Run your query to insert the line inside that while-loop.
if ($file = fopen("words.txt", "r")) {
while (($line = fgets($file)) !== false) {
// Run the query
// Perhaps $line = trim($line) ?
// Pseudo-query: INSERT INTO tablename (word) VALUES ('$line')
// $line is the content of each line individually */
}
fclose($file); // Close the file at the end
} else {
/* File could not be opened */
}
You can use trim()
on each $line
to remove any whitespaces (would be $line = trim($line);
).
Also note that when inserting values into a database, you should use parameterized queries to ensure you avoid any security issues (SQL injection) and issues with quotes.