mysql - php import csv file contents into database

不言
Release: 2023-03-01 07:46:02
Original
3012 people have browsed it

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);
Copy after login

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');
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!