Submit Textfile Contents To Database

Discussion in 'PHP' started by poblo10, Oct 9, 2010.

  1. #1
    So I have a large text file & I want to submit its contents to a database.

    How exactly would I got about doing that?

    Note: The text file is in a format of
    cat
    dog
    fish

    (Return has been pressed after everyword)

    Also would there be a way to assign a variable to each word
    So like line 1 would be say "cat" but would be declared like $line1 so I can also manipulate the text.

    Thanks in advance.
     
    Last edited: Oct 9, 2010
    poblo10, Oct 9, 2010 IP
  2. JoelLarson

    JoelLarson Peon

    Messages:
    61
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Well if you're looking to submit each return, the code would be similar to this:

    <?php
    
    $link = mysql_connect('localhost', 'root', '');
    mysql_select_db('testing', $link);
    
    $sql = "INSERT INTO `records` (`id`, `entry`) VALUES (NULL, '%s') LIMIT 1;";
    
    $file = file_get_contents('/home/joel/Documents/large_file.txt');
    $file_lines = explode("\n", $file);
    
    foreach($file_lines as $line)
    {
    	mysql_query(sprintf($sql, $line));
    }
    Code (markup):
    I haven't personally tested this code out, but it's essentially how it will work. If this isn't what you were looking for, please be more specific as to what data you want to go where. :)
     
    JoelLarson, Oct 9, 2010 IP
  3. poblo10

    poblo10 Peon

    Messages:
    135
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Ya i think that may work, I'll test that out.

    Also would there be a way to assign a variable to each word
    So like line 1 would be say "cat" but would be declared like $line1 so I can also manipulate the text.
     
    poblo10, Oct 9, 2010 IP
  4. JoelLarson

    JoelLarson Peon

    Messages:
    61
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    $file = file_get_contents('/home/joel/Documents/large_file.txt');
    $file_lines = explode("\n", $file);
    Code (markup):
    These two lines retrieve the text file as a string, then separates the string into segments between each return key.

    To access line 20 of your file, you would use:
    $file_lines['20'];
    Code (markup):
    This applies to every line of the code, and you can find out how many lines you have by:
    count($file_lines)
    Code (markup):
    The array variables always start at zero, so your limit is:
    $file_lines[(count($file_lines) - 1)]
    Code (markup):
     
    JoelLarson, Oct 9, 2010 IP