Connecting Tech Pros Worldwide Forums | Help | Site Map

Extracting individual lines from a Multiline text box for processing

Newbie
 
Join Date: Nov 2008
Posts: 1
#1: Nov 2 '08
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's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,751
#2: Nov 3 '08

re: Extracting individual lines from a Multiline text box for processing


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:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // This is the string, delimited by a comma, rather than a new-line.
  3. $rawString = "piece1,piece2,piece3";
  4.  
  5. // Split the string into pieces
  6. $pieces = explode(",", $rawString);
  7.  
  8. // Build the top of the INSERT query
  9. $sql = "INSERT INTO `myTable`(`myField`) VALUES\n";
  10.  
  11. // Build the rest of the INSERT query by re-assembling the
  12. // pieces.
  13. $sql .= "('";
  14. $sql .= implode("'), ('", $pieces);
  15. $sql .= "')"; 
  16. ?>
  17.  
Now the $sql variable should be somewhat like:
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO `myTable`(`myField`) VALUES
  2. ('piece1'), ('piece2'), ('piece3')
  3.  
Be careful tho if this data is coming from a client.
Make sure you run it through the mysql_real_escape_string function first, and perhaps even the trim function to.
Reply