Now all the content in the CSV file needs to be read and inserted into the database
Reply content:
Now all the content in the CSV file needs to be read and inserted into the database
You refer to Phpexcel This class library to see
$file = fopen (' xxx.csv ', ' R '), while ($data = Fgetcsv ($file)) { $result [] = $data;}//$result array is the content of CVS, put $ The result is good to save to the database. Fclose ($file);
First use Fgetcsv to convert the CSV file into an array, then open the transaction, loop Insert, 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]); This assumes that the contents of each line are ID, title and content $stmt->execute (); If the insertion fails, update the 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 ');