Skip to content

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

  • by
how-to-import-data-from-text-file-into-MYSQL

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

<?php
$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 -> http://php.net/manual/en/function.list.php            
        list($message) = $lineArr;
        // and then insert data
        $con->query("INSERT INTO notes (message) VALUES ('$message')");
    }
    fclose($handle);
}
?>

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!

Leave a Reply

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