douxiyi2418
2015-10-27 21:42
浏览 79
已采纳

如何使用文本文件创建SQL表条目?

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

图片转代码服务由CSDN问答提供 功能建议

我有一个如下所示的文本文件:

   WPG GRIFFON,WIIRHAIRED 
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)或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');“);

但是,我总是收到一个错误并且它崩溃了网页,因为我无法将文件转到 b e读取并保存。

  $ handle = @fopen(“names.txt”,“r”); 
while(!feof($ handle))//循环直到 文件结尾。
 {
 $ buffer = fgets($ handle,4096); 
 
 $ sql =“INSERT INTO data_table ....”
mysql_query($ sql,$ conn)或die(mysql_error(  )); 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dstxpei5823 2015-10-28 01:15
    已采纳

    Do you need to use INSERT statements? There are two other very viable options (a little out of the box, maybe):

    1. LOAD DATA: SQL that loads pre-built CSV data into a table. See the MySQL manual and this SO thread

    Example 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);
    
    1. 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
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题