将文本文件导入数据库
是否可以使用phpmyadmin导入文本文件?将文本文件导入数据库
在文件中是这样的:
country - county/city
USA - Florida/Orlando
USA - Florida/Miami
USA - Washington/Washington DC
Switzerland - Solothurn/Grenchen
文件有超过3000行
现在我想导入到我的CATERGORY表 表是这样的:
id | parent_id | name
国家和县都在档案中多次。在我的数据库中,我只需要它一次。 城市是在文件中唯一
我可以做到这一点与phpmyadmin或它是唯一可能的PHP? 任何人都可以告诉我如何做到这一点。 感谢
这是我自己的解决方案
<?php
require 'funcs/connect.php';
$file = 'cities.txt';
$file_handle = fopen($file, 'r');
while (!feof($file_handle)) {
$line = fgets($file_handle);
$text_line = explode("-",$line);
echo $text_line[0];
echo $text_line[1];
echo $text_line[2];
if ($text_line[1] != "")
{
$name = $text_line[1];
$stmt = $handler->prepare("SELECT name FROM news_cat WHERE name = '$name'");
$stmt->execute();
$count = $stmt->rowCount();
if ($count >= 1)
{
echo"Kanton schon vorhanden";
}
else
{
$stmt = $handler->prepare("INSERT INTO news_cat(name,parent_id)VALUES('$name','0')");
$stmt->execute();
}
}
if ($text_line[2] != "")
{
$name = $text_line[2];
$canton = $text_line[1];
$stmt = $handler->prepare("SELECT name FROM news_cat WHERE name = '$name'");
$stmt->execute();
$count = $stmt->rowCount();
if ($count >= 1)
{
echo"Bezirk schon vorhanden";
}
else
{
$stmt = $handler->prepare("SELECT id FROM news_cat WHERE name = '$canton'");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
$parent_id = $row->id;
}
$stmt = $handler->prepare("INSERT INTO news_cat(name,parent_id)VALUES('$name','$parent_id')");
$stmt->execute();
}
}
if ($text_line[0] != "")
{
$name = $text_line[0];
$bezirk = $text_line[2];
$stmt = $handler->prepare("SELECT id FROM news_cat WHERE name = '$bezirk'");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
$parent_id = $row->id;
}
$stmt = $handler->prepare("INSERT INTO news_cat(name,parent_id)VALUES('$name','$parent_id')");
$stmt->execute();
}
echo "<br>";
}
fclose($file_handle);
?>
phpMyAdmin的可以帮助这一点,但你必须与其他程序来整理数据,让您使用相同的分隔符(无论是-
或/
应精细)。您可以在任何文本编辑器(或您最喜欢的命令行工具; sed,awk,perl等)中使用“搜索和替换”来执行此操作。只要确保您的数据不包含您要替换的字符(例如,在“萨克森安哈尔特”中)。
然后,您可以从phpMyAdmin的“导入”选项卡执行标准导入。它看起来像你需要使用以下参数:(你上面的选择基础上)/
或-
- 列(空白)
- 列逃脱(空)终止了与
- 线:
auto
问题后几分钟或几小时的思考abaout 我的意思是与phpmyadmin是不可能的,因为州和市我必须添加parent_id –
哦,因为它不是在您的文本文件我认为这是一个自动增量主键。 –
很高兴你找到了解决方案。 –
您可以使用FREAD()从文件中逐行读取和爆炸您的字符串,以获得申请您需要为您分贝。 – Mattia
“美国 - 佛罗里达/奥兰多”这条线应该是“美国”,“佛罗里达”还是“奥兰多”,或者它应该是名为“美国 - 佛罗里达/奥兰多”的一排吗?如果是第一个选项,parent_id应该插入一个合适的值(USA是佛罗里达州的parent_id,佛罗里达州是奥兰多的parent_id)? – steven
没有在我的数据库中它应该是3行 –