Importing p/ Mysql from TXT

Asked

Viewed 444 times

1

I have a txt file coming from a database that separates the items with a space type TAB, the item first is the product name, the second item of txt is the value, type this, I need to know how to make php import this way separating the fields correctly, which can indicate me to study as directly as possible some tutorial for example ?

Language: PHP

  • You need to import this only once or it will be a feature of your system?

  • You will get the option Import file, and you will forget all previous database and replace with current data.

1 answer

2


Basic solution

 // Abrir documento fonte
 $name_src = "nome_documento.txt";
 $h_src = fopen($name_src,"r");


 // Leitura linha depois linha até o final
 while (($str_src = fgets($h_src)) !== false)
 {

    // Explode sobre TAB
    $tab = explode("\t",$str_src);

    // Prepara o query (exemplo com 3 valors per linha)
     $query_insert = "INSERT INTO TAB_GARDE_ACT "
     ."( "
     ."campo1, "
     ."campo2, "
     ."campo3 "
     .") "
     ."VALUES "
     ."("
     ."'".$tab[0]."', "
     ."'".$tab[1]."', "
    ."'".$tab[2]."' "
    .") ";

     //Fazer o query (depende do que vc usa Mysql, mysqli, dbp, postgress...)
     $result = sql_query($connector,$query_insert);
 }

 // Fechar documento
 fclose($h_src);

Need (normal!) to open the connection with the BDD. If you have a lot of data, you can use a so SQL call. To do this, you need to use mysql_insert_array().

  • 1

    Just one note: mysql_* functions have been deprecated since PHP 5.5. Prefer to use Mysqli or PDO. See more here: http://www.ultimatephp.com.br/php-por-que-nao-utilizar-funcoes-mysql To insert several values at once, see this post: http://rberaldo.com.br/insindomultiplos-registros-em-tabela-de-banco-data

  • Valeu iiiiiiii

Browser other questions tagged

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