How do I read this text file and Insert into MySQL?

前端 未结 5 711
萌比男神i
萌比男神i 2020-12-18 16:07

sample

user id  User Name
   U456      Mathew 
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500

相关标签:
5条回答
  • 2020-12-18 16:49

    LOAD DATA INFILE

    Example:

    NOTE: if you run this from Windows you need to escape the forward slashes in the file path.

    EXAMPLE:

    C:\\path\to\file.txt
    

    Looks like:

    C:\\\\path\\to\\file.txt
    

    Here is the query:

    LOAD DATA INFILE '/path/to/sample.txt' 
    INTO TABLE `database_name`.`table_name` 
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\r\n'
    IGNORE 1 LINES
    (
    user_id, user_name
    )
    
    0 讨论(0)
  • 2020-12-18 17:00

    Use the fopen function of PHP to access and read the file.. From there on the rest is pretty much simple. Read the file line by line and insert the values into the database.

    http://us3.php.net/manual/en/function.fopen.php

    The above link gives a very good description of how the fopen function works.. Using a loop will be easy in this task.

    0 讨论(0)
  • 2020-12-18 17:02

    Using PHP, Possibly Something similar to this:

    $file = "/path/to/text/file.txt";
    $fp = fopen($file, "r");
    $data = fread($fp, filesize($file));
    fclose($fp);
    

    The above reads the text file into a variable

    $output = explode("\n", $output);
    foreach($output as $var) {
    $tmp = explode("|", $var);
    $userId = $tmp[0];
    $userName = $tmp[1];
    

    Tell it to explode at each Endline and then store the data in temp variables

    $sql = "INSERT INTO table SET userId='$userId', userName='$userName'";
    mysql_query($sql);
    

    Execute the query for each line

    0 讨论(0)
  • 2020-12-18 17:02

    Depends. If the two fields are separated using a TAB character, then fgetcsv($f,1000,"\t") would work to read in each line. Otherwise use substr() if it's a fixed width column text file to split up the fields (apply trim() eventually).

    Loop over the rows and fields, and use your database interface of choice:

    db("INSERT INTO tbl (user_id, user_name) VALUES (?,?)", $row);
    
    0 讨论(0)
  • Delete the first line and use this command

    LOAD DATA INFILE 'C:\\sample.txt' 
    INTO TABLE Users 
    FIELDS TERMINATED BY ' '  
    LINES TERMINATED BY '\r\n';
    

    For more information visit http://tech-gupshup.blogspot.com/2010/04/loading-data-in-mysql-table-from-text.html

    0 讨论(0)
提交回复
热议问题