Wednesday, October 17, 2007

Import xls into Mysql

hi,
to import xls file into mysql you can run this script, please make sure that xls file name is correct and placed in the same directory where you script file is.


$db_username="db_username"; //database user name
$db_password="db_password";//database password
$db_database="database_name"; //database name
$db_host="localhost";


mysql_connect($db_host,$db_username,$db_password);
@mysql_select_db($db_database) or die( "Unable to connect to database.");


$handle = fopen("test.xls", "r"); //test.xls excel file name
if ($handle)
{
$array = explode("\n", fread($handle, filesize("test.xls")));
}

$total_array = count($array);
$i = 0;

while($i < $total_array)
{
$data = explode(",", $array[$i]);
$sql = "insert into test values ('$data[0]','$data[1]')"; // i have two fields only , in oyour case depends on your table structure
$result = mysql_query($sql);

$i++;
}
echo "completed";

1 comment:

Anonymous said...

Hello Gurmukh,
I have written a small code that stores referral activities ie who sends a traffic to my site and how many down line members are signing up under a particular referral link but it seems there are some bugs in it. will you please post a referral code in your blog or send me at my email address.
rajpal@himarticles.com

Thanks