Extracting individual lines from a Multiline text box for processing

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • swanc04
    New Member
    • Nov 2008
    • 1

    #1

    Extracting individual lines from a Multiline text box for processing

    Greetings Master of PHP /bow

    I would like to preform the following task but I'm unable to figure out how, I never really got into Arrays and usually just use work arounds. I would be very greatful for your assistance.

    1. I want to Copy and Paste data from my computer into a text field (Multiline)

    2. When I click submit the php code should then take all of the data from the text field and seperate each line into a seperate variable / array entry.

    3. I then need to enter that data into a mysql database (I know how to work with DBs just not the extract from array and enter bit)

    I'm not sure if it can be done without an array? I guess you could enter the data into the database on each cycle of the extraction process?

    There is no set format to the data, it will look something like this.

    French
    German
    Spanish-Portugal
    Chineese

    and in my database I would like a field called Language with 1 row per language.

    etc...

    Thanking you in advance for your help!
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    This is actually quite simple to do once you get used to using arrays.
    ... Which is true of most things I guess :)

    In this case, you can simply split your string into pieces using the explode function. This will create an array, each element containing one piece.

    Then you could either use a foreach loop loop to insert each piece into your database.
    Or, my personal preference, use the implode function to re-assemble the pieces into a VALUE clause for a single INSERT query.

    Consider this:
    [code=php]
    <?php
    // This is the string, delimited by a comma, rather than a new-line.
    $rawString = "piece1,piece2, piece3";

    // Split the string into pieces
    $pieces = explode(",", $rawString);

    // Build the top of the INSERT query
    $sql = "INSERT INTO `myTable`(`myFi eld`) VALUES\n";

    // Build the rest of the INSERT query by re-assembling the
    // pieces.
    $sql .= "('";
    $sql .= implode("'), ('", $pieces);
    $sql .= "')";
    ?>
    [/code]
    Now the $sql variable should be somewhat like:
    [code=sql]
    INSERT INTO `myTable`(`myFi eld`) VALUES
    ('piece1'), ('piece2'), ('piece3')
    [/code]

    Be careful tho if this data is coming from a client.
    Make sure you run it through the mysql_real_esca pe_string function first, and perhaps even the trim function to.

    Comment

    Working...