如何在上传之前验证CSV内容并使用php将其保存到msql数据库?

时间:2018-03-27 10:04:33

标签: php regex

我在互联网上到处搜索但是我无法找到一个完美的解决方案,关于如何在上传之前验证CSV内容并将其保存到数据库,我使用msqli作为数据库,PHP使用语言脚本。例如,我在localhost数据库中有3列:

这些是我在locahost数据库和CSV文件中制作的以下标题(1。)日期(2.)电子邮件(3.)电话号码。

在上传并保存到localhost数据库之前,应该满足内容的限制是ff: 对于日期:它应该是mm / dd / yy ----> 1/31/2018或12/31/2018 对于电子邮件:它应该是name@domain.com ----> saffron@gmail.com 对于数字:它应该只有12位数字,格式为----> 0906-021-0156

如果这些限制完全符合,CSV文件将被上传并保存到数据库,否则会抛出错误或弹出消息。

我真的不知道如何开始执行程序。我是PHP新手,所以请帮助我。

这是我工作的代码,我在这里堆叠......

<?php

$dbHost = 'localhost';
$dbUsername = '';
$dbPassword = 'root';
$dbName = 'dbUpload';

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_error) {
    die("Unable to connect database: " . $db->connect_error);
}

if(isset($_POST['submit'])){
	
	$row = 1;
	$mycsvfile = array(); //define the main array.
	
	if ($_FILES['csv']['size'] > 0) {
    	//get the csv file 
    		$file = $_FILES['csv']['tmp_name']; 
    		$handle = fopen($file, "r");
    		$i = 0;
    		
      		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

      		$num = count($data);	
        	$row++;
	
    		$mycsvfile[] = $data; //add the row to the main array.
    		
    		$headerDate = $mycsvfile[0][0];
    		$headerEmail = $mycsvfile[0][1];
    		$headerPhone = 	$mycsvfile[0][2];

    		if ($headerDate !== 'Date' || $headerEmail !== 'Email' || $headerPhone !== 'Phone Number') {
    				$qstring = '?status=invalid_header';    				
    				fclose($handle); 				
    			}
    			
    			else {
    				if ($i > 0) {
           
           			$import = "INSERT into upload (techDate, techEmail, techPhone)values('$data[0]','$data[1]','$data[2]')";
           			
           			$db->query($import);
           			$qstring = '?status=succ';
    				 	}
    			}
    		$i++;	    			
		}	
		fclose($handle);
		
		

}
else{
	$qstring = '?status=err';
  	}
}
header("Location: uploadvalid.php".$qstring);
?>

1 个答案:

答案 0 :(得分:0)

您可以使用preg_match()功能。

我从StackOverflow获取了正则表达式(用于日期和电子邮件)。链接在此代码下方。我为你的手机格式制作了正则表达式。

<?php

$dbHost = 'localhost';
$dbUsername = '';
$dbPassword = 'root';
$dbName = 'dbUpload';

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_error) {
    die("Unable to connect database: " . $db->connect_error);
}

if(isset($_POST['submit'])){

    $row = 1;
    $mycsvfile = array(); //define the main array.

    if ($_FILES['csv']['size'] > 0) {
        //get the csv file 
            $file = $_FILES['csv']['tmp_name']; 
            $handle = fopen($file, "r");
            $i = 0;


            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

            $num = count($data);    
            $row++;

            $mycsvfile[] = $data; //add the row to the main array.

            $headerDate = $mycsvfile[0][0];
            $headerEmail = $mycsvfile[0][1];
            $headerPhone =  $mycsvfile[0][2];

            if ($headerDate !== 'Date' || $headerEmail !== 'Email' || $headerPhone !== 'Phone Number') {
                    $qstring = '?status=invalid_header';                    
                    fclose($handle);                
                }

                else {
                    if ($i > 0) {

                        $patternDate = '^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$';

                        $patternEmail = '(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])';

                        $patternPhone = '0906\d021\d0156';

                        // Check if the row has the correct format
                        if (preg_match($data[0], $patternDate)
                            && preg_match($data[1], $patternEmail)
                            && preg_match($data[2], $patternPhone)) {

                            // Format is OK, let's insert

                            $import = "INSERT into upload (techDate, techEmail, techPhone)values('$data[0]','$data[1]','$data[2]')";

                            $db->query($import);
                            $qstring = '?status=succ';

                         } else {
                             // The row doesn't have the right format
                             echo "The row $row doesn't have the right format";
                         }
                     }
                }
            $i++;                   
        }   
        fclose($handle);



}
else{
    $qstring = '?status=err';
    }
}
header("Location: uploadvalid.php".$qstring);
?>

link to the StackOverflow date regex

link to the StackOverflow email regex

相关问题