Import csv file content from mysql-php to the database

Source: Internet
Author: User
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 ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.