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

如何使用文本文件创建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());
}
  • 写回答

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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)