将csv文件导入mysql时避免添加数据

时间:2014-11-14 10:09:09

标签: php mysql csv

好的,我在这里遇到了一些严重的问题。我是这个网站的新手,也是处理通过PHP导入CSV数据的新手,也是编程方面的新手。

当我将csv文件导入mysql时,我的数据库文件中有一些添加的数据 这是我将csf文件上传到mysql的脚本

  <?php
include '../php/koneksi.php';
if(isset($_POST["Import"])){


        $filename=$_FILES["file"]["tmp_name"];


         if($_FILES["file"]["size"] > 0)
         {

            $file = fopen($filename, "r");
             while (($Data = fgetcsv($file, 1000, ",")) !== FALSE)
             {

              //It wiil insert a row to our subject table from our csv file`
               $sql = "INSERT into raport (`no_induk`, `nama`, `kelas`, `jurusan`,mapel, `semester`, `nilai`, `deskripsi`) 
                    values(
                            '".trim($Data[0], '"')."',
                            '".trim($Data[1], '"')."', 
                            '".trim($Data[2], '"')."',
                            '".trim($Data[3], '"')."',
                            '".trim($Data[4], '"')."',
                            '".trim($Data[5], '"')."',
                            '".trim($Data[6], '"')."',
                            '".trim($Data[7], '"')."'
                        )";
             //we are using mysql_query function. it returns a resource on true else False on error
              $result = mysql_query( $sql);
                if(! $result )
                {
                    echo "<script type=\"text/javascript\">
                            alert(\"Invalid File:Please Upload CSV File.\");
                            window.location = \"upload.php\"
                        </script>";

                }

             }
             fclose($file);
             //throws a message if data successfully imported to mysql database from excel file
             echo "<script type=\"text/javascript\">
                        alert(\"CSV File has been successfully Imported.\");
                        window.location = \"upload.php\"
                    </script>";



             //close of connection
            mysql_close; 



         }
    }    
?>       

0 个答案:

没有答案