将.txt解析为csv并在php中插入数据库

时间:2018-05-08 06:08:53

标签: php

代码:

<?php
    if(isset($_POST['submit']))
    {
        $filename = $_FILES['field']['name'];
        $path = "attandance_file/";
        $move = move_uploaded_file($_FILES['field']['tmp_name'],$path.$_FILES['field']['name']);
        $path_file = "attandance_file/".basename($_FILES['field']['name']);
        $fileObj = fopen( $path_file, "rt" );
        while (($line = fgets( $fileObj )))
        {
            $members = explode("\n", $line);
            foreach($members as $row)
            {
                $rowss = explode("  ",$row);
                foreach($rowss as $data)
                {
                    $query = "insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('".$data."')";
                    echo $query;
                }
            }
        }
    }
?>

在这段代码中我上传了一个.txt文件,然后点击提交,然后读取.txt文件,这是可读的,之后我使用explode函数在新行上显示视图,但是当我将数据插入表格然后打印查询它看起来像:

insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('No')
insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('TMNo')
insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('EnNo')
insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('Name')
insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('INOUT')
insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('Mode')
insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('DateTime')

但我想要这个

 insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('No','TMNo','EnNo','Name','INOUT','Mode','DateTime')

我该怎么做?请帮帮我。

谢谢

2 个答案:

答案 0 :(得分:1)

这样做的方法是直接使用数据库驱动程序,并且非常容易地完成。

在您的代码中删除此内容:

foreach($rowss as $data){
  $query = "insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('".$data."')";
}

并将其更改为以下内容:

$sql = "insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values(".trim(str_repeat('?,', count($rowss)),',').")";

现在,您的$sql字符串已准备好用作PDO或MySQLi中的预准备语句,并将$rowss解析为执行参数,如下所示:

$stmt = $pdo->prepare($sql);
if(!$stmt->execute($rowss)){
  echo "Failed to execute query.";
}

答案 1 :(得分:0)

您确定您拥有所有需要的记录价值吗?

device.flashMode = AVCaptureFlashModeAuto;

更改为:

$rowss = explode("  ",$row);
foreach($rowss as $data)
{
    $query = "insert into attandance(No,TMNo,EnNo,Name,INOUT,Mode,DateTime)values('".$data."')";
    echo $query;
}