Now you need to read and insert all contents in the csv file into the database. now you need to read and insert all contents in the csv file into the database.
Reply content:
Now you need to read all the contents in the csv file and insert it to the database.
Please refer to the phpexcel class library.
$ File = fopen('xxx.csv ', 'r'); while ($ data = fgetcsv ($ file) {$ result [] = $ data ;} // The $ result array is the content of CVS. save $ result to the database. Fclose ($ file );
First use fgetcsv to convert the CSV file into an array, and then enable transactions and insert them cyclically. 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]); // assume that the content in each row is ID, title, and content $ stmt-> execute (); // If insertion fails, change to 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 ');