Upload . txt to Mysql database

Asked

Viewed 250 times

0

Hello,

I would like to upload a file .txt which meets the layout as follows (following 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 today is simple, but only matters the first column:

<?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 there’s no separation of the columns being made, but it’s the most I could find at the moment.

I don’t code in OO yet.

Thank you!

  • the table users are with which layout? (ie the fields for insertion, you did not specify in SQL this is not very appropriate.)

  • 1

    True @Virgilionovic is right. You should play it safe and specify columns and their values

  • @Virgilionovic I did not specify the columns at first because the layout is all columns present in this table, but I will specify!

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 is not required, but I recommend to play it safe and specify the column name in the query as well.

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

  • Thank you @Miguel, perfectly meets the proposal!

  • You’re welcome @jvbarsou, I’m glad you solved

  • in fact did not know much about implode and explode, now it will be very useful hehehehe

  • Gradually you learn, "practice makes the master" @jvbarsou

Browser other questions tagged

You are not signed in. Login or sign up in order to post.