Monday, February 14, 2011

Import an .csv file to my sql data base

To import an .csv file todata base of my sql. Youcan easily

import an .csv file to data base by this script


//impot an ,csv file to my sql data base


//Database connection

$con=mysql_connect("localhost","root","");

if(!$con)
{
die('Could not connect: ' . mysql_error());

}
mysql_select_db("artpoly1",$con);



//query on the pree of submit button after selecting file

if(isset($_POST['submit']))
{

$fname = $_FILES['file_name']['name'];


$chk_ext = explode(".",$fname);


if(strtolower($chk_ext[1]) == "csv")

{

// print_r($_FILES['file_name']['tmp_name']);


$filename = $_FILES['file_name']['tmp_name'];


$handle = fopen($filename,'r');


$sql2="INSERT into

import(`file_name`,`timestamp`)values('".$fname."','".date('Y-m-d H:i:s')."')";


mysql_query($sql2);


$id = mysql_insert_id();


while (($data = fgetcsv($handle,1000, ","))!== FALSE)
{

//insert query to the database


$sql ="INSERT into import_sanmar


(`IMPORT_ID`,`UNIQUE_KEY`,`PRODUCT_TITLE`,`SPEC_SHEET`,`PRICE_TEXT`,

`SANMAR_MAINFRAME_COLOR`,`MILL`)

values('".$id."','".mysql_escape_string($data[0])."',

'".mysql_escape_string($data[1])."','".mysql_escape_string($data[2])."',

'".mysql_escape_string($data

[3])."','".mysql_escape_string($data[4])."','".mysql_escape_string($data[5])."','".my

sql_escape_string($data[6])."')";

//$sql2="INSERT into

import(`sel_file`,`timestamp`)values('$filename','".date('Y-m-d H:i:s')."')";

//$sql1=mysql_query("delete from import where UNIQUE_KEY=0");

mysql_query($sql) or die(mysql_error());

//mysql_query($sql2);

// to delete the first row of field name

//$sql1=mysql_query("delete from import_sanmar where IMPORT_ID=0");


$sql1=mysql_query("delete from import_sanmar where UNIQUE_KEY=0");

}




fclose($handle);

echo "Successfully Imported";
}

else

{

echo "Invalid File";

}

}
?>


form action="'' method='post' enctype="multipart/form-data">


import file: <input type="file" name="file_name" /><br />
<input type="submit" name="submit" />

/form>


by useing this script you can able to import the csv filedata to mysql database.

3 comments:

  1. Τhis paгagraph is гeally a fastidious
    one it aѕsiѕts new іnteгnеt pеople, ωho are wishing for blοgging.


    mу ωeb blog; raspberry ketone

    ReplyDelete
  2. Hі, Νeat рoѕt. Theге is
    a problem аlong ωith уour wеb ѕitе
    in ωeb explorer, wоuld chеck thіѕ?
    IE still is thе mагkеt leader anԁ a huge соmponеnt tο οther folκs wіll miss уour fantastic wгiting due to this pгoblеm.


    my sіtе - credit card debt settlement

    ReplyDelete
  3. Thаnks for any otheг excеllent article.
    The plaсe elsе could anуbody get thаt type of
    info in ѕuсh а perfect wаy
    of wгіting? I hаνe а pгesentation subsеquеnt ωeek, and Ι'm on the look for such info.

    Also visit my webpage cheap car insurance

    ReplyDelete