Now we need to read and insert all the contents in the csv file into the database
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');