TransWikia.com

Importing CSV into database table not working?

WordPress Development Asked by Coder Sathya on December 15, 2021

global $wpdb;

if (isset($_POST["import"])) {

$fileName = $_FILES["file"]["tmp_name"];

if ($_FILES["file"]["size"] > 0) {

    $file = fopen($fileName, "r");

    while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {


        $table_name = 'sas' ;


        $wpdb->insert( 


            $table_name,


            array( 


            'category' => '" . $column[0] . "',

            'temple' => '" . $column[0] . "'

        )
            );





    }
}
}

I want to import csv directly into the core wordpress database table ‘sas’ .The csv contains some records with the structure of the table i have created…But the import is not successfull..

One Answer

You can use Load data infile MySQL Query instead of looping through each entry.

Doc: https://dev.mysql.com/doc/refman/8.0/en/load-data.html

For example:

$wpdb->query(
                $wpdb->prepare(
                        "LOAD DATA LOCAL INFILE %s INTO TABLE sas FIELDS TERMINATED BY ',' ENCLOSED BY %s IGNORE 1 LINES (@category,@temple) SET category = @category, temple = @temple;", $_FILES['file']['tmp_name'], '"'
                )
        );

Make sure that fields from file are properly mapped to those in DB. Also it will change as per your file formatting. Hope this helps.

Note: Please check for syntax error/ typos, code is not tried or tested.

Answered by Aniruddha Gawade on December 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP