10-09-2010, 09:29 PM
(10-09-2010, 07:27 PM)xbiohazardx Wrote: So I have a large text file & I want to submit its contents to a database.
How exactly would I got about doing that?
Note: The text file is in a format of
cat
dog
fish
(Return has been pressed after everyword)
Also would there be a way to assign a variable to each word
So like line 1 would be say "cat" but would be declared like $line1 so I can also manipulate the text.
Thanks in advance.
You aren't going to be assigning each line as its own variable. You'd need to know exactly how many lines there are in the file and then it wouldn't be extensible nor flexible. Rather you can use an array. Simply put, an array is a container of values. PHP offers a very simple way to feed each line of a file directory into an array via its file () function.
From there you'd want to build a SQL INSERT statement. Supposing you're using MySQL, you can insert multiple rows in one INSERT statement by creating a list of VALUE pairs. Example:
Code:
INSERT into table_name (col1, col2) VALUES (someData, someData), (moreData, moreData), (evenMoreData, evenMoreData)
An example:
PHP Code:
<?php
mysql_connect ("server", "username", "password");
mysql_select_db ("database_name");
// Build the lines array, thus $lines[0] will be the first and etc.
$lines = array_map ('trim', file ("file", FILE_SKIP_EMPTY_LINES));
$sql = "INSERT INTO table_name (column_name) VALUES ";
foreach ($lines as $index => $curLine)
{
$sql .= "('$curLine')";
// count () returns the number of lines, but it isn't zero-based, so we add 1 to the line number to make sure it isn't the last element to avoid the trailing comma
if (count ($lines) != ($index + 1))
{
$sql .= ", ";
}
}
// And query it
mysql_query ($sql);
?>
Ho, ho, ho! Well, if it isn't fat stinking billy goat Billy Boy in poison!
How art thou, thou globby bottle of cheap, stinking chip oil?
Come and get one in the yarbles, if ya have any yarbles, you eunuch jelly thou!
How art thou, thou globby bottle of cheap, stinking chip oil?
Come and get one in the yarbles, if ya have any yarbles, you eunuch jelly thou!