2016-11-07 26 views
0

タイトルに説明されているように、CSVファイルをPHPページにアップロードしてテーブルにデータをインポートしようとしています。 これは私がCSVファイルからPHPを使用してMysqlテーブルにデータをインポート

<?php 
 
\t \t \t \t \t 
 
\t \t \t \t \t $servername = "localhost"; 
 
\t \t \t \t \t $username = "root"; 
 
\t \t \t \t \t $password = ""; 
 
\t \t \t \t \t $dbname = "Test"; 
 

 
\t \t \t \t \t // Create connection 
 
\t \t \t \t \t $conn = new mysqli($servername, $username, $password, $dbname); 
 
\t \t \t \t \t // Check connection 
 
\t \t \t \t \t if ($conn->connect_error) { 
 
\t \t \t \t \t \t die("Connection failed: " . $conn->connect_error); 
 
\t \t \t \t \t } 
 
\t \t \t \t \t 
 
\t \t \t \t \t 
 
?> 
 

 
<html> 
 

 
\t <body> 
 
\t \t 
 
\t \t <form name="import" method="post" enctype="multipart/form-data"> 
 
\t \t <input type="file" name="file" /><br /> 
 
     <input type="submit" name="submit" value="Submit" /> 
 
\t \t </form> 
 
\t \t 
 
\t \t <?php 
 
if(isset($_POST["submit"])) 
 
{ 
 
$file = $_FILES['file']['tmp_name']; 
 
$handle = fopen($file, "r"); 
 
$c = 0; 
 
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) 
 
{ 
 
$name = $filesop[0]; 
 
$email = $filesop[1]; 
 
    
 
$sql = "INSERT INTO `xl` (`Name`, `Email`) VALUES ('$name','$email')"; 
 

 
} 
 
    
 

 
if ($conn->query($sql) === TRUE) { 
 
\t echo "You database has imported successfully"; 
 
} else { 
 
    echo "Error: " . $sql . "<br>" . $conn->error; 
 
} 
 
} 
 

 
?> 
 
\t </body> 
 

 
</html>

問題は、ファイルを提出する際、私のファイルの最後の行のみがテーブルに挿入されます、ということである

EggSlabからもらったコードです。コードをcsvファイルのすべての行に挿入するための変更を提案しますか?参照の例以下

+1

あなたのwhileループの各反復のためのクエリを実行します。ここでは、最後に要求を実行するだけですので、一度にそれはあなたのCSVの最後の行です – Berserk

+0

なので、わかりませんがwhileループでif else文を動かそうとします – Berserk

+0

whileループ。 –

答えて

1

これはあなたの問題を解決する必要があります。ループ内でクエリを実行していませんでした。

\t \t <?php 
 
if(isset($_POST["submit"])) 
 
{ 
 
$file = $_FILES['file']['tmp_name']; 
 
$handle = fopen($file, "r"); 
 
$c = 0; 
 
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) 
 
{ 
 
    $name = $filesop[0]; 
 
    $email = $filesop[1]; 
 
    
 
    $sql = "INSERT INTO `xl` (`Name`, `Email`) VALUES ('$name','$email')"; 
 
    if ($conn->query($sql) === TRUE) { 
 
\t echo "You database has imported successfully"; 
 
    } else { 
 
    echo "Error: " . $sql . "<br>" . $conn->error; 
 
    } 
 
} 
 
    
 

 
    
 
} 
 

 
?>

+0

はい、これは完全に機能しました。ご回答いただきありがとうございます。 –

0

CSVファイルのインポート:

<?php 
      $file = $_FILES['file']['tmp_name']; 

      //Read the file 
      $content = file_get_contents($file); 
      //Split file into lines 
      $lines = explode("\n", $content); 

      //Find columns by reading first line 

      for ($i = 1; $i <= 310; $i++) { 
       $data = explode("\t", $lines[$i]); 
       $name = $filesop[0]; 
       $email = $filesop[1]; 

       $sql = "INSERT INTO `xl` (`Name`, `Email`) VALUES ('$name','$email')"; 

     } 
    } 
関連する問題