0

I've multiple TXT files that contain columns in the following format:

id:category:topic:date

They're all lined up under one another. i.e.

1:category:topic:date

2:category:topic:date

3:category:topic:date

is it possible to import this file into my MySQL database?

3

1 Answer 1

2

With PHPMyAdmin

On the import tab, you can upload a CSV file. Upload your file, select format 'CSV', and set:

  • Columns separated with: :
  • Columns enclosed with: (empty)

With PHP

You can write a small PHP program to do that. First, read in the file:

$fh = fopen('the-file.txt', 'r');

Now, $fh is a handler to read the-file.txt. Now we can use fgetcsv():

while (($data = fgetcsv($fh, 1000, ':', '')) !== false) {
    // insert data in database
}

$data is an array of all the data in the record.


An example with PDO and a prepared statement:

// prepare the statement to insert a new record
$stmt = $pdo->prepare("INSERT INTO `some_table` (`id`, `category`, `topic`, `date`) VALUES (?, ?, ?, ?)");
// read the file
$fh = fopen('the-file.txt', 'r');
while (($data = fgetcsv($fh, 1000, ':', '')) !== false) {
    $stmt->execute($data);
}

This would assume the column names are 'id', 'category', 'topic' and 'date'.

The number 1000 is the max line length. You can set it to 0, for no maximum length, but this is slightly slower. See the docs for more information.

5
  • is there not a faster method using i.e. phpmyadmin? We are talking about 10M+ lines.. Jan 20, 2015 at 10:56
  • @Removed ah, I was confused because you used the 'php' tag. I modified the answer.
    – user1544337
    Jan 20, 2015 at 10:58
  • 1
    why not fgetcsv() with a : delimiter
    – Mark Baker
    Jan 20, 2015 at 11:00
  • @MarkBaker I didn't know the function existed, thanks.
    – user1544337
    Jan 20, 2015 at 11:01
  • @CamilStaps I get the error "Invalid parameter for CSV import: Columns escaped with" should I use " even though that is not how they're escaped? Jan 20, 2015 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.