Magento – Read csv file and insert on a table using SQL sentences.

Home Magento TopicsMagento – Read csv file and insert on a table using SQL sentences.
mage+php

Magento – Read csv file and insert on a table using SQL sentences.

No Comments

Magento – Read csv file and insert on a table using SQL sentences.

You may occasionally you may need to incorporate information from an external data source to Magento but this action can be hard job due to the volume of data. We present a solution that will make easier this purpose: import information from a .csv file directly into a Magento table using SQL sentences!

Using SQL sentences, you will avoid runtime problems in particular if you are using servers with low performance.

 /**
 * Read csv file and insert values into a table using SQL sentences.
 */
 public function uploadCSVFile()
 {
 
    //*** Adapter Definition.
    $adapter = Mage::getModel('core/resource')->getConnection('core_write');
 
    //*** Commit existing transactions (use carefuly!)
    if ($adapter->getTransactionLevel > 0) {
	$adapter->commit();
    }
 
    //*** Define Isolation level: in the example, records inserted could be readed after commit!
    $adapter->query('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
    $adapter->beginTransaction();
    try {
 
       $tablename = $this->_getTableName('your_table_name');
 
       //*** Truncate table. 
       $sqlquery_truncate = 'TRUNCATE TABLE '.$tablenameto;
       $adapter->query($sqlquery_truncate);
       $adapter->commit();
 
 
        //*** Inform CSV file path. In the example, file is already uploaded in the server!
        $fileToImp = '';
        $fileToImp = Mage::getBaseDir('base').'/your_folder/your_file_name.csv';
 
 
        //*** CSV file import. In the example we are importing 3 columns!
        $row = 1; 
        $separatorChar = ',';
	$fp = fopen ($fileToImp,"r");  
 
 
        while ($data = fgetcsv ($fp, 1000, $separatorChar))  
        {  
 
	//*** Checkings. In the example the first column can not be empty.
	if ($data[0] == ''){
	    //*** Error!
            throw new Exception('First column is empty!. No valid record number %d: ',$row);
 
	}else{
	   $num = count ($data);
	   $sqlquery_insert = 'INSERT INTO '.$tablenameto;
	   $sqlquery_insert .= ' (column1,column1,column1) VALUES (';
	   $sqlquery_insert .= '\''.$data[0].'\''.','.'\''.$data[1].'\''.','.'\''.$data[2].'\''.')';	
 
           $adapter->query($sqlquery_insert );
	   $adapter->commit();
 
	}
	$row++;
     }  
 
     fclose ($fp); 
 
     //*** Unset Variables
     unset($adapter);
 
 
     } catch (Exception $e) {
        // Rollback if exception!
	$adapter->rollBack();
        var_dump($e->getMessage());
     }
 }
[bws_google_captcha]

Leave a Reply

Your email address will not be published. Required fields are marked *