为了账号安全,请及时绑定邮箱和手机立即绑定

php 与 mysql:导入 .csv 分隔空间

php 与 mysql:导入 .csv 分隔空间

PHP
千巷猫影 2023-12-15 16:09:34
如何将此文件导入到mysql,行之间有空格? 通过 phpmyadmin 这是可能的,但我需要通过网站来完成。<?php// Check if file was uploaded & there were no errorsif ($_FILES && $_FILES['csv-file']['error'] == 0) {    $extension = pathinfo($_FILES['csv-file']['name'],PATHINFO_EXTENSION);    // Check if extension is csv then proceed to import    if($extension == 'csv'){        // Open file for reading        $file = fopen($_FILES['csv-file']['tmp_name'], 'r');        // Loop through all rows of file and insert them to database table        while (!feof($file)) {            // Get current row as recordset            $row = fgetcsv($file);            if (!empty($row)) {                $data = [];                $data['numbers'] = htmlentities($row[0]);                $data['tids'] = htmlentities($row[1]);                $data['date'] = htmlentities($row[2]);                $data['time'] = htmlentities($row[3]);                $data['zero'] = htmlentities($row[4]);                $data['terminal_sn'] = htmlentities($row[5]);                $data['space'] = htmlentities($row[6]);                $records[] = $data;                mysqli_query($dbcon,"INSERT INTO employees (".implode(",",array_keys($data)).") VALUES ('".implode("','",array_values($data))."')");            }        }    }else{?>这是我的 .csv 文件,其中包含数据:10222157120501 T0040922 07/09/2020 18:13:56 0 315-525-348 110223157120502 T0040923 07/09/2020 18:15:24 0 318-027-497 110224157120503 T0040924 07/09/2020 18:15:36 0 316-176-614 110225157120504 T0040925 07/09/2020 18:16:25 0 317-377-077 1
查看完整描述

1 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

// prepare the insert query once outside the loop

$sql = 'INSERT INTO employees (`numbers`, `tids`, `date`, `time`, 

                               `zero`, `terminal_sn`, `space`)

            VALUES(?,?,?,?,?,?,?)';

$stmt = $dbcon->prepare($sql);


if (($handle = fopen($_FILES['csv-file']['name'], "r")) !== FALSE) {

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

        //             space delimiter      ^

        

        // bind the columns to the query parameters

        $stmt->bind_param('sssssss', $row[0], $row[1], $row[2], $row[3],

                                     $row[4],$row[5], row[6]);

        // execute the query with parameters replaced with data

        $stmt->execute();

    }

    fclose($handle);

}



查看完整回答
反对 回复 2023-12-15
  • 1 回答
  • 0 关注
  • 113 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信