Importing CSV into database table not working?

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..

Topic csv import bulk-import database Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.