I have a text file that looks like this:
WPG GRIFFON, WIREHAIRED
AFG HOUND, AFGHAN
IBI HOUND, IBIZAN
WOF HOUND, IRISH WOLF
OTT HOUND, OTTER
PHA HOUND, PHAROAH
DER HOUND, SCOTTISH DEER
JIN JINDO
...
and I am trying to rewrite this line of code so it says the names of the dogs
$link = mysqli_connect($servername, $username, $password, $db) or die(mysqli_error($link));
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `description` (`descID` int(10) NOT NULL AUTO_INCREMENT, `desc` text NOT NULL, PRIMARY KEY (`descID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
mysqli_query($link, "INSERT INTO description
(descID
, desc
) VALUES(1, 'description 1'),(2, 'description 2'),(3, 'description 3'),(4, 'description 4');");
However, I always get an error and it crashes the webpage, because I can't get the file to be read and saved.
$handle = @fopen("names.txt", "r");
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 4096);
$sql = "INSERT INTO data_table ...."
mysql_query($sql,$conn) or die(mysql_error());
}
Do you need to use INSERT
statements? There are two other very viable options (a little out of the box, maybe):
LOAD DATA
: SQL that loads pre-built CSV data into a table. See the MySQL manual and this SO threadExample usage (from the linked SO thread):
LOAD DATA INFILE 'path/file.csv'
INTO TABLE tbl_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '
'
(column1, column2, column3);
mysqlimport
: If you have access to the MySql shell, you can use this to import a physical CSV to the db. See the MySQL manual or this post from a random google click