Monday, August 12, 2013

Importing Excel data in MySql via PHP

Hi Guys,

So i decided to venture into PHP but then I came to a halt when i wanted to import excel data into Mysql. I finally got a way around this and thought i should share with with anyone who has the same problem. so here it is.....

If you want to import an Excel file into MySQL database, you can do it easily using PHP code. First, of all  you will need to download some prerequisites library:


Once you have downloaded both files, please upload them to your web server.  To work around a small bug in PHPExcelReader, copy oleread.inc file from the Excel directory into a new path: Spreadsheet/Excel/Reader/OLERead.php
The PHPExcelReader code will expect OLERead.php to be in that specific location. Once that is complete, you’re ready to use the PHPExcelReader class. I made an example Excel spreadsheet like this:
<?php
require_once 'Excel/reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('yourExceldataSheet.xls');

$conn = mysql_connect("dataBaseHostName","DataBaseUserName","DataBasePassword");
mysql_select_db("DataBaseName",$conn);

for ($x=2; $x<=count($data->sheets[0]["cells"]); $x++) {
    $name = $data->sheets[0]["cells"][$x][1];
    $extension = $data->sheets[0]["cells"][$x][2];
    $email = $data->sheets[0]["cells"][$x][3];
    $sql = "INSERT INTO mytable (name,extension,email) 
        VALUES ('$name',$extension,'$email')";
    echo $sql."\n";
    mysql_query($sql);
}
?>
If you are getting an error like this–      
 Deprecated: Assigning the return value of new by reference is deprecated in                  E:\wamp\www\ARE\application\Excel\reader.php on line 262

 then look for this code
$this->_ole =& new OLERead(); and remove the & in front =, 
 new code $this->_ole = new OLERead();