Upload .txt for MySQL database

0

Hello,

I would like to upload a file .txt that meets the layout as follows (follow the example of two lines of the file):

9787546;488464;2016-12-11;Carlos Fonseca;carlos.fonseca
9787547;464664;2016-12-11;Rogério Barros;rogerio.barros

The file maintains this layout and has more than 3 thousand lines.

I would like to know more or less a script that treats the lines, differentiating in columns each data.

What I have currently simple, but only the first column imports:

<?php
$file = fopen('../files/docs/libs/newUsers.txt', 'r');

while(!feof($file)){
    $data = fgets($file);
    $query = mysqli_query($con,"insert into users values '({$data})'");
}

I know that no separation of the columns is being made, but it was the maximum I found at the moment.

I have not yet coded in OO.

Thank you!

    
asked by anonymous 27.12.2016 / 13:14

1 answer

1

Try this:

$file = fopen('../files/docs/libs/newUsers.txt', 'r');

while(!feof($file)){
    $data = explode(';', fgets($file)); // separar valores pelos ; que estão no ficheiro
    $query = mysqli_query($con, 'INSERT INTO users (COL1, COL2,COL3, COL4, COL5) VALUES (' .implode(', ', $data). ')');
}

It's not required, but I'd like to play safe and specify the name of the columns in the query as well.

You should replace the COL .. By the name of the respective columns that you have in the users table, the first one ( COL1 ) corresponds to the first value etc ...

    
27.12.2016 / 13:30