[PHP/Mysql] How To Load Any Data File Into Database Table

Hello Friends, In this post I will explain you how to load data file which data is separated by one separator (, or | or -) in database table by only single mysql query. Some days ago I was working on one project in which I have to fetch one data feed from other server to website server via FTP functions of PHP then load that file in my sql database table and show that data in website. So because of this feature I need one query by which I can load data in database table by one query.

Below is query by which we can load data of file in database table.

$file_name = "/file_path/filename.txt";
$table_name = 'load_data';
$terminate_str = '|';
$query_load = "LOAD DATA LOCAL INFILE '$file_name' INTO TABLE $table_name FIELDS TERMINATED BY '$terminate_str' LINES TERMINATED BY '\n'";

Now explanation of this query. First field $file_name is file name which you want to load into database table/ You can put file to any other folder on server but you have to give path related to that folder. To load this file it is must that you have this file on your server. If it is on other server then you have to fetch it and copy it to same server your database exists. Now second variable $table_name is name of table of database in which you want to load data of file. Third variable is $terminate_str is the string by which your data is separated in your file.

Now when you execute this query it loads all data to your database table. You must have related fields in database table as your text file having else it will not load data correctly.

It is little bit tricky job so let me know if you need any help. I am PHP Freelancer and WordPress Developer So If you have any projects related to PHP or any Open Source then contact me.