[HOW TO] Upload CSV file into MYSQL database using PHP

CSV (Comma Separated Values) is used mainly while storing and retrieving the data from the database to csv file. Follow the steps and technique and you can easily upload the created .csv file into the database.

First create the database in your phpmyadmin in localhost of your browser. I have created the database named as "new_database". Then Create table with four columns naming id, firstname, lastname and address. 

Now move to wamp\www folder and create folder named "csv_folder" and create the php file inside it. If you are using xamp the project folder will be at htdocs folder in xamp folder.

Then open php editor and create a new file named as "file_upload_form.php" and paste the code given below.
<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
<h2>File Upload</h2>
 <form action="upload_csv.php" method="post"
   enctype="multipart/form-data" >
  <label for="file">Filename:</label> 
  <input type="file" name="file" id="file" required><br>
  <input type="submit" name="submit" value="Submit">
 </form>
</body>
</html>
Now create upload_csv.php file and paste the code given below:
<?php
// Saving CSV file into database
//if ($_FILES["file"]["type"] == "text/csv")
  //{
 $connect = mysql_connect("localhost","root","");
 $db= mysql_select_db("new_database",$connect);
   //Import uploaded file to Database
    $handle = fopen("upload/csv_file.csv", "r");
    while (($data = fgetcsv($handle, 1000)) !== FALSE) {
        $import="INSERT into csv_testing(firstname,lastname,address) 
                 values('$data[0]','$data[1]','$data[2]')";
        mysql_query($import) or die(mysql_error());    }
     fclose($handle);
     print "Uploaded to database successfully";     
?>
All the datas contained in .csv file are successfully inserted into database. When large amount of data is to be uploaded into the database then it can be implemented.
[HOW TO] Upload CSV file into MYSQL database using PHP [HOW TO] Upload CSV file into MYSQL database using PHP Reviewed by RefreshIt on 12:23:00 AM Rating: 5

No comments:

Powered by Blogger.