CSV文件数据插入数据库

时间:2015-08-01 11:18:00

标签: php csv

我使用下面的代码将csv文件数据插入到数据库中,数据必须插入到数据库中,但是循环不能控制文件结尾,这意味着该文件中只有1条记录(列名)也在那里)但是循环循环2次第二次电子邮件发送到电子邮件

define('csv','C:/wamp/www/csvfile/');

$csv_file = "csv/Customer.csv";     

$csvfile = fopen($csv_file, 'r');

$theData = fgets($csvfile);

$i = 0;

if(file_exists("csv/Customer.csv")) {

        while(!feof($csvfile)) {

            $csv_data[] = fgets($csvfile, 1024);

            $csv_array = explode(",", $csv_data[$i]);   

            if($csv_array[0] != '' AND $csv_array[1] != '' AND $csv_array[2] != '' AND $csv_array[3] != ''){        

                $insert_offline_cust = "insert into Registration(CustomerID,name,CustType,Status) values ('".$csv_array[0]."','".$csv_array[1]."',,'".$csv_array[2]."','".$csv_array[3]."')";       

                mssql_query($insert_offline_cust)  or die("Insert Error"); 

                $i++;                                                                           

            }else{              
                $to = "abc@gmail.com";      
                    $subject = "CSV file data";
                        $message = "Some value missing<br>";                                                            
                        $headers = "From: XYZ" . "\r\n";
                        $headers .= "MIME-Version: 1.0" . "\r\n";
                        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

                    //echo $message;exit;   

                    // send mail to customer.
                    mail($to,$subject,$message,$headers);
                    $i++;                   
            }

        }
        fclose($csvfile);

1 个答案:

答案 0 :(得分:0)

你在这里:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>INPUT CSV FILE</title>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<form action="1.php" method="post" name="frmcsv" enctype="multipart/form-data">
<p><input type="file" name="csv"/></p>
<p><input type="submit" name="submit" value="SEND"/></p>
</form>
<?php
if(isset($_POST['submit'])){
    $filename=$_FILES['csv']['tmp_name'];
    $type=$_FILES['csv']['type'];
    if($type=='application/vnd.ms-excel'){
        $fop=fopen($filename,"r");
        while(($file=fgetcsv($fop,1000,","))!==false)
    {
        echo $file[0].','.$file[1].','.$file[2].','.$file[3].','.$file[4].'<br/>';

    }
    fclose($fop);
    }
    else{
        echo'NOT CORRECT FORMAT';   
    }
}
?>  
</body>
</html>

回显文件内容后,您可以插入数据库然后发送邮件。