【问题标题】:How to check each column data in a csv file, before importing into mysql database in php?如何在 php 中导入 mysql 数据库之前检查 csv 文件中的每一列数据?
【发布时间】:2019-03-30 12:55:00
【问题描述】:

我的列标题是 id、name、phone。如果我在 id 列中给出名称,则数据未插入,但消息显示为“成功导入”。我想显示“数据未正确定义”之类的消息。导入mysql前如何验证代码?

我尝试检查 if 和 else 条件,但没有得到我需要的实际结果。

$sql = "INSERT IGNORE INTO `all`(`id`, `name`,`phone`)   VALUES ('".$getData[0]."','".$getData[1]."','".$getData[2]."')";
$result = mysqli_query($conn, $sql);
if($result)
 {
echo  "<script type=\"text/javascript\">alert(\"CSV File has been successfully Imported.\");                    
  }</script>";
else {
echo "<script type=\"text/javascript\"> alert(\"Invalid File Format/ Data Please check file is csv and data as per headings.\");      
}</script>";
}

我希望警报消息为“不正确的数据”,但得到“成功导入”。

【问题讨论】:

    标签: php mysqli import-csv


    【解决方案1】:

    您可以使用 is_int() 来检查值(在您的情况下为 $getData[0])是否为整数。

    在查询中添加值之前

    if(!is_int($getData[0])
    { 
        echo "<script type=\"text/javascript\"> alert(\"Improper Data.\");      
        }</script>";
    
    }
    else
    {
        // insert query code here
    }
    

    【讨论】:

      【解决方案2】:

      验证应该在任何 INSERT 之前完成,这样你就可以做到:

      <?php
      
      //validation of csv
      
      if (false === validateCsvRow($getData)) {
          echo "data is not properly defined";
      
          // or better to throw an exception - uncomment to see difference
          // throw new \InvalidArgumentException("data is not properly defined");
      
          die; //end script execution
      }
      
      // if validation is okay script continues.
      
      $sql = "INSERT IGNORE INTO `all`(`id`, `name`,`phone`)   VALUES ('".$getData[0]."','".$getData[1]."','".$getData[2]."')";
      
      $result = mysqli_query($conn, $sql);
      if($result)
       {
      echo  "<script type=\"text/javascript\">alert(\"CSV File has been successfully Imported.\");                    
        }</script>";
      else {
      echo "<script type=\"text/javascript\"> alert(\"Invalid File Format/ Data Please check file is csv and data as per headings.\");      
      }</script>";
      }
      
      
      function validateCsvRow(array $data) : bool
      {
          $result = 1;
      
          //check if id is not set
          if (!isset($data[0]) {
              $result *= 0;
          }
      
          //check if id is not integer
          if (!is_int($data[0]) {
              $result *= 0;
          }
      
          //check if name is not set
          if (!isset($data[1]) {
              $result *= 0;
          }
      
          //check if name is not string
          if (!is_string($data[1]) {
              $result *= 0;
          }
      
          $minimumNameLength = 1; //number of characters
      
          //check if name has at least n characters
          if (!strlen($data[1]) < $minimumNameLength) {
              $result *= 0;
          }
      
          //return 1 => true if all was ok
          //or 0 => false if at least one check was not ok.
          return (bool) $result;
      
      }
      

      上面的代码使用打字,如果你使用的是旧的php版本变化

      function validateCsvRow(array $data) : bool
      

      到:

      function validateCsvRow($data)
      

      【讨论】:

        【解决方案3】:

        CSV 中的字段顺序可能会有所不同,例如。第 0 列不能总是“id”。

        考虑一下这个 CSV:

        name, id, phone
        'Alice', 1, 1234
        'Bob', 2, 5678
        

        还有这段代码:

        $sql = "INSERT IGNORE INTO `all`(`id`, `name`,`phone`) VALUES (?, ?, ?)";
        $stmt = $db->prepare($sql);
        $header = null;
        while($row = fgetcsv($handle)) {
            if ($header == null) {
                $header = $row;
                continue;
            }
            $data = array_combine($header, $row);
            // $data is now an assoziative array, eg. you can grab "id" by name
        
            $stmt->execute([ $data['id'], $data['name'], $data['phone'] ]);
        }
        

        【讨论】:

          猜你喜欢
          • 2017-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-06
          • 1970-01-01
          • 1970-01-01
          • 2017-11-15
          • 1970-01-01
          相关资源
          最近更新 更多