PHP正则表达式和CSV验证

时间:2015-07-05 21:17:09

标签: php mysql regex csv

我正在尝试创建一个CSV Checker,它将已检查的数据插入数据库,并将任何不成功的数据添加到.txt文件中。 我试图使用正则表达式来验证我插入的数据,没有任何验证工作的while循环和插入正常,但一旦使用正则表达式它不起作用。

<?php
    include_once('connection.php');
    error_reporting(E_ALL);
    date_default_timezone_set('Europe/London');
    $date = date('d/m/y h:i:s a', time());
    $filetxt = "./errors.txt";
    $errors = array();
    $var1 = 5;
    $var2 = 1000;
    $var3 = 10;
    $sql = '';

    if(isset($_POST["Import"]))
    {
        echo $filename=$_FILES["file"]["tmp_name"]; 
        if($_FILES["file"]["size"] > 0)
        {
            $file = fopen($filename, "r");
            while(($emapData = fgetcsv($file, 10000, ",")) !==FALSE)
            {
                if(isset($_GET['strProductCode']))
                {
                    $emapData[0] =  $conn->real_escape_string(trim($_POST['strProductCode']));

                    if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode']))
                    {
                        $errors['strProductCode'];
                    }
                }
                if(isset($_GET['strProductName']))
                {
                    $emapData[1] =  $conn->real_escape_string(trim($_GET['strProductName']));
                    if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductName']))
                    {
                        $errors['strProductName'];
                    }
                }
                if(isset($_GET['strProductDesc']))
                {
                    $emapData[2] =  $conn->real_escape_string(trim($_GET['strProductDesc']));
                    if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductDesc']))
                    {
                        $errors['strProductDesc'];
                    }
                }
                if(isset($_GET['intStock']))
                {           
                    if (!preg_match("^[0-9]", $_POST['intStock']))
                    {
                        $errors['intStock'];
                    }
                }
                if(isset($_GET['intPrice']))
                {
                    if (!preg_match("[0-9]", $_POST['intPrice']))
                    {
                        $errors['intPrice'];
                    }
                }
                if(isset($_GET['dtmDiscontinued'])){
                    if($emapData[6] == preg_match("[a-zA-Z]", $_POST['dtmDiscontinued']))
                    {

                        $emapData[6] = $date;
                        echo $date;
                    }else{
                            $emapData[6] = Null;
                        }
                }
                if(count($errors > 0))
                {
                    // errors 
                    $write = "$emapData[0], $emapData[1], $emapData[2], $emapData[3], $emapData[4], $emapData[5], $emapData[6]\r\n";     
                    file_put_contents($filetxt , $write , FILE_APPEND);

                }else{
                    // insert into Database
                        $sql = "INSERT INTO tblproductdata(strProductCode, strProductName, strProductDesc, intStock, intPrice, dtmAdded, dtmDiscontinued) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$date','$emapData[6]')";
                    $res=$conn->query($sql);
                    }

            }
            fclose($file);
            echo "CSV File has successfully been Imported";
            echo "<br>";
            echo "Any errors within the CVS Database are reported here.";
            echo "<br>";
            $fh = fopen($filetxt, 'r');
            $theData = fread($fh, filesize($filetxt));
            fclose($fh);
            echo $theData;

        }else{
            echo "Invalid File: Please Upload a Valid CSV File";    
        }
            header("Location: index.php");
    }
?>

我对PHP的了解不是很好,但这是我最好的尝试。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的代码中存在多个问题。让我们从正则表达式和错误检查开始:

  1. 您的某些表达无效。请注意,每个表达式在表达式的beginng和end结束时都需要分隔符。在某些表达式(如^[0-9])中,这些分隔符缺失。另请注意,使用^作为正则表达式的分隔符不是一个好的选择,因为^字符在正则表达式中也有特殊含义。

    这实际上应该导致PHP警告。我看到你已启用error_reporting;您还应该查看display_errors设置。

  2. 正如我的评论所述,您不会为$errors数组分配任何值。语句$errors['strProductName']本身并不会改变数组;这意味着$errors将始终为空。你可能意味着做一些事情:

    $errors['strProductName'] = TRUE;
    
  3. 您实际上正在检查count($errors > 0)您应该检查count($errors > 0)的位置。 count($errors > 0)转换为count(TRUE)count(FALSE),均为1。

  4. 其他一些说明:

    1. 有时,您检查$_GET['strProductCode'],然后使用$_POST['strProductCode']
    2. 您不会为每次迭代重置$errors数组。这意味着对于您读取的每一行,$errors变量仍将包含上一次迭代中的错误。因此,第一个无效行也会导致所有后续行被识别为无效。
    3. 当其中一个参数格式无效时,您会注册一个错误,但是当其中一个参数未设置时(即isset($_POST[...])FALSE时)则不会注册。他们每个人都应该是......像这样:

      if (isset($_POST['strProductCode'])) {
          $emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
          if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode'])) {
              $errors['strProductCode'] = TRUE;
          }
      } else {
          $errors['strProductCode'] = TRUE;
      }
      
相关问题