Import Data From txt File to MySQL Using Php

0
776

Welcome back to shortlearner.com .Today we will learn how to insert data from a text file into mysql database by using php .

import txt data into mysql
we have two files, one is employee.txt file which contain employees name and email address, and another one is index.php file which contains code of fetching data from file and inserting into database.

DATABASE CREATION :

create database test;

CREATE DATABASE TABLE:

CREATE TABLE `employee`(`id` INT(11) NOT NULL AUTO_INCREMENT,`name` VARCHAR(255) NULL,`email` VARCHAR(255) NULL, PRIMARY KEY(`id`));

Text File(employee.txt)

ankit,ankit@gmail.com

swapnil, swapnil@gmail.com

shefali, shefali@gmail.com

abhishek, abhishek@gmail.com

php code: index.php

//Connecting to database

$conn = mysqli_connect('localhost','root','','demo');

if(!$conn)
{
    die(mysqli_error());
}

//read text file and insert data into database

<?php
$conn = mysqli_connect('localhost','root','','test');

$open = fopen('employee.txt','r');

while (!feof($open)) 
{
	$getTextLine = fgets($open);
	$explodeLine = explode(",",$getTextLine);
	
	list($name,$email) = $explodeLine;
	
	$qry = "insert into emails (`name`,`email`) values('".$name."','".$email."')";

	mysqli_query($conn,$qry);
}

fclose($open);


?>

In the above code firstly we open a employee.txt using reading (r) mode. Then we use a while loop using feof() function and make sure loop

must be iterated till the end of file. Then we stored file line in the $getTexLine variable and then convert that line into an array by using
comma. we already knew that we have 2 type of data on each line so I used list() function and create 4 variables which are $name, $email. After

that we create a mysql insert statement and add data into table. This process will continue until employee.txt content ends.