mysql-php Import CSV file contents to the database

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