Home>Article>Backend Development> mysql - php import csv file contents into database

mysql - php import csv file contents into database

不言
不言 Original
2018-05-23 16:03:58 2888browse

Now we need to read and insert all the contents in the csv file into the database

Reply content:

Now we need to read and insert all the contents in the csv file into the database

Please refer to the phpexcel class library to take a look

$file = fopen('xxx.csv', 'r'); while($data = fgetcsv($file)) { $result [] = $data; } //$result数组就是CVS的内容啦,把$result存到数据库就好。 fclose($file);

First use fgetcsv to convert the CSV file into an array, then start the transaction and insert in a loop. The code example is as follows:

query('SET AUTOCOMMIT=0'); $db->query('START TRANSACTION'); foreach($arr as $row) { $stmt = $db->prepare('INSERT INTO posts (id, post_title, post_content) VALUES (?,?,?)'); $stmt->bind_param('iss', $row[0], $row[1], $row[2]); //这里假设每行内容分别为ID,标题和内容 $stmt->execute(); //如果插入失败,改为更新 if($stmt->affected_rows == 0 || $stmt->affected_rows == -1) { $stmt = $db->prepare('UPDATE posts SET post_title = ?, post_content = ? WHERE id = ?'); $stmt->bind_param('ssi', $row[1], $row[2], $row[0]); $stmt->execute(); if($stmt->affected_rows == 0 || $stmt->affected_rows == -1) { echo 'Import '.$row[0].' failed!'."\n"; } } } $db->query('COMMIT'); $db->query('SET AUTOCOMMIT=1');
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn