2016-02-12 193 views
0

是否可以使用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? 任何人都可以告訴我如何做到這一點。 感謝

+1

您可以使用FREAD()從文件中逐行讀取和爆炸您的字符串,以獲得申請您需要爲您分貝。 – Mattia

+0

「美國 - 佛羅里達/奧蘭多」這條線應該是「美國」,「佛羅里達」還是「奧蘭多」,或者它應該是名爲「美國 - 佛羅里達/奧蘭多」的一排嗎?如果是第一個選項,parent_id應該插入一個合適的值(USA是佛羅里達州的parent_id,佛羅里達州是奧蘭多的parent_id)? – steven

+0

沒有在我的數據庫中它應該是3行 –

回答

0

這是我自己的解決方案

<?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); 


?> 
1

phpMyAdmin的可以幫助這一點,但你必須與其他程序來整理數據,讓您使用相同的分隔符(無論是-/應精細)。您可以在任何文本編輯器(或您最喜歡的命令行工具; sed,awk,perl等)中使用「搜索和替換」來執行此操作。只要確保您的數據不包含您要替換的字符(例如,在「薩克森安哈爾特」中)。

然後,您可以從phpMyAdmin的「導入」選項卡執行標準導入。它看起來像你需要使用以下參數:(你上面的選擇基礎上)/-

  • 列附帶:使用分離

    • 列(空白)
    • 列逃脫(空)終止了與
    • 線:auto
  • +0

    問題後幾分鐘或幾小時的思考abaout 我的意思是與phpmyadmin是不可能的,因爲州和市我必須添加parent_id –

    +0

    哦,因爲它不是在您的文本文件我認爲這是一個自動增量主鍵。 –

    +0

    很高興你找到了解決方案。 –