Wednesday, 26 December 2012

Reading CSV file in php | PHP Tutorial For Beginners


This tutorial shows you how to read csv file using php and store the data in to database.
CSV is a file format which store comma separated values. We read the csv file line by line and store the value into database.We must be aware of importing data into a database. Data used for importing is normally in the form of a text file. Sometimes these files are called a comma-separated value file, which will normally have a .csv extension.

Let’s start the coding part.

Step 1:-
You have to create one CSV file and store the data in it. We will use php code to read this file content and store into database. In my case the csv file contain following data:

Name                    Address              Phone
ABC                       XYZ                    12345

Step 2:-
Now create one php file and put the bellow code in it and save it as upload.php

<?php
/*-----------------------------------Database connection---------------------------------*/

$hostname_conn = "localhost";
$database_conn = "upload";
$username_conn = "root";
$password_conn = "";
 $conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn); 
mysql_select_db($database_conn, $conn) or die("could not select db");
/*------------------------------------------------------------------------------------------*/
if(isset($_FILES['userfile']['name'])) {
$ext = strrchr($_FILES['userfile']['name'],".");
if($ext==".csv") {

// store file in temporary folder.
move_uploaded_file($_FILES['userfile']['tmp_name'],"files/".$_FILES['userfile']['name']); 

// Move file from temporary folder to our location(I have used files folder).
$file = file("files/".$_FILES['userfile']['name']); 

// Reading content of the file.
foreach($file as $key=>$line) { 

// I'm reading from second line.
if($key>=1) { 
$var = explode(",",$line);

// Storing content in to database.
$query = "insert into mytable values('".$var[0]."','".$var[1]."',".$var[2].")"; 
mysql_query($query) or die();
}
}
} else {
$error = 'File Should be in csv format. You have upload in '.$ext.' format.';
}
}
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Upload File</title>

</head>

<body>
<table width="500" border="1" align="center" cellpadding="1" cellspacing="0" height="300">
  <tr>
    <td valign="top">
<table width="100%"  border="0" cellspacing="1" cellpadding="5">
<tr>
<td colspan="2" valign="top">
<h3>Upload File</h3>
<?php  echo $error; ?>
<form action="" method="post" enctype="multipart/form-data" name="form1">
<p>
<input name="userfile" type="file" id="userfile" size="45">
</p>
<p>
<input type="submit" name="Submit" value="Upload">
</p>
</form>
</td>
    </tr>
    </table>
    </td>
</tr>
</table>
</body>
</html>


No comments:

Post a Comment