如何使用textfile创建SQL表项?

时间:2015-10-27 21:42:47

标签: php mysql database web crash-reports

我有一个看起来像这样的文本文件:

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 
...

我正在尝试重写这行代码,因此它会显示狗的名字

$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 descriptiondescIDdesc)VALUES(1,'说明1'),(2, '描述2'),(3,'描述3'),(4,'描述4');");

但是,我总是收到错误并且崩溃了网页,因为我无法读取并保存文件。

$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());
}

1 个答案:

答案 0 :(得分:0)

需要使用INSERT语句吗?还有另外两个非常可行的选择(可能有点开箱即用):

  1. LOAD DATA:将预先构建的CSV数据加载到表中的SQL。请参阅the MySQL manualthis SO thread
  2. 示例用法(来自链接的SO线程):

    LOAD DATA INFILE 'path/file.csv'
    INTO TABLE tbl_name 
    FIELDS TERMINATED BY ',' 
    ENCLOSED BY '"' 
    LINES TERMINATED BY '\n' 
    (column1, column2, column3);
    
    1. mysqlimport:如果您有权访问MySql shell,则可以使用它将物理CSV导入数据库。请参阅the MySQL manualthis post from a random google click