Jump to content

Multiline textbox - parse each line and save in DB


phAze

Recommended Posts

Hello all,

 

I have what I'm sure is a very easy question and I'm a bit embarrassed to be asking this but I cannot seem to think it out.  I want to have a multi-line textbox (textarea) that will allow someone to enter data on each line.  I then want to break the textarea line by line and save each line to my db.

 

I know how to connect and insert into my db but I'm struggling thinking how to break the textarea by each line and then saving each of those lines as a new insert.

 

Any help would be appreciated, thanks!

Keep in mind that lines can wrap in a textarea, so even if it looks like three lines it may be one long line. If you want to separate by where someone presses enter then this should work (textarea is the name of the textarea):

if(isset($_POST['textarea'])) {
    $lines = array_map('trim', explode("\n", $_POST['textarea']));
    foreach($lines as $line) {
        //insert into db
    }
}

 

If you want it to wrap somewhat like a textarea, this could work:

if(isset($_POST['textarea'])) {
    //60 is the number of columns (or letters to wrap at)
    $lines = array_map('trim', explode("\n", wordwrap($_POST['textarea'], 60, "\n")));
    foreach($lines as $line) {
        //insert into db
    }
}

dcro2,

 

WOW!  Thanks for the very fast response and explanation!  I didn't even think about text wrapping!  The code you provided worked like a charm.. My next concern is how do I not insert blank lines?  Such as if there is a blank line in between actual data, or if there is a blank line at the end?

 

Thanks again!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.