How to import data from text file into MYSQL database table using PHP ?


When working with databases it is always necessary to import data or schemas. In this article we describe the process of importing data from a text file into a MySQL database.

Data in a text file can be:

  • stored as columns of fixed width;
  • separated by a delimiter;
  • of free format.

The method of inserting the data, as shown below

$con= new mysqli('localhost','userName','Password','dbName');
$handle = fopen("student.txt", "r");
if ($handle) 
	while (($line = fgets($handle)) !== false) 
    	$lineArr = explode("\t", "$line");
        var_dump($lineArr); //to make sure array is ok
        // instead assigning one by one use php list ->            
        list($message) = $lineArr;
        // and then insert data
        $con->query("INSERT INTO notes (message) VALUES ('$message')");

Good luck and I hope this article can be useful. See you in the next article…

If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!

By Rodney

I’m Rodney D Clary, a web developer. If you want to start a project and do a quick launch, I am available for freelance work.

Leave a Reply

Your email address will not be published. Required fields are marked *