逐行解析文本文件并将数据存储在 MYSQL 数据库中

Parse text file line by line and store data in MYSQL database

此时我不关心安全问题。我已经在这段代码上停留了 4 天。请帮忙。这是我此时的代码。我正在我的 php 网络应用程序中上传一个文本文件。上传成功。我将文件移动到一个目录,这也有效。我只需要在 foreach 循环期间的解析算法方面的帮助。它会存储这两个值一次,然后就不会再这样做了。我已经将数据库设置保存在我的文件中。文本文件以制表符分隔,所有数据类型都在数据库中 table.

     $file_name= $_FILES['file1']['name'];
     $add= "uploads/$file_name";
     $move = move_uploaded_file($_FILES['file1']['tmp_name'], $add);
     $get = file_get_contents("$add");
     $delimiter = "\n";
     $line = explode($delimiter, $get);
     foreach ($line as $value => $data) {
         $delimiter = "\t";
         $tab = explode($delimiter, $data);
         $datetime = $tab[0];
         $deltatime = $tab[1]; 
         $sql = "INSERT INTO RobotData (datetime, deltatime) VALUES('$datetime', '$deltatime')"; 
         $store = mysqli_query($conn, $sql);
     }

尝试这样的事情并告诉我

$file_name = $_FILES['file1']['name'];
$add = "uploads/$file_name";
$move = move_uploaded_file($_FILES['file1']['tmp_name'], $add);

$handle = fopen($add, "r");

if ($handle) {

    while (($line = fgets($handle)) !== false) {

        $arr = explode("\t", $line);
        $datetime = mysqli_real_escape_string($arr[0]);
        $deltatime = mysqli_real_escape_string($arr[1]);

        $sql = "INSERT INTO RobotData (datetime, deltatime) VALUES('$datetime', '$deltatime')";
        $store = mysqli_query($conn, $sql);
    }

    fclose($handle);
} else {
    // error opening the file.
} 

编辑

在字符串中添加了转义特殊字符以用于 SQL 语句

这是我现在使用的代码...

     $file_name= $_FILES['file1']['name'];
     $add= "uploads/$file_name";
     $move = move_uploaded_file($_FILES['file1']['tmp_name'], $add);
     $handle = fopen($add, "r");
     if ($handle) {
         while (($line = fgets($handle)) !== FALSE) {
            $delimiter = "\t";
            $tab = explode($delimiter, $line);
            $datetime = $tab[0];
            $deltatime = $tab[1];  
             $sql = "INSERT INTO RobotData (datetime, deltatime) VALUES ('$datetime', '$deltatime')"; 
             $store = mysqli_query($conn, $sql);
              if($store === TRUE) {
                  fclose($handle);
                 $delete= unlink($add);
                 echo "YOU DID IT!!";
             }
             else {
                 fclose($handle);
                 $delete= unlink($add);
                 echo "YOU SUCK!!";
             }
         }
    }
    else {
         fclose($handle);
         $delete= unlink($add);
         echo "Something went wrong";
    }

尝试 LOAD DATA INFILE - 创建它是为了从文本文件中快速加载大量数据:

LOAD DATA LOCAL INFILE '/full/path/to/text/file'
INTO TABLE RobotData
COLUMNS TERMINATED BY '\t'
LINES TERMINATED BY '\n';