Harsh Sanghani
Harsh Sanghani

Reputation: 1712

Combine two textarea value with line breaks using PHP

I have two different textarea and I want to store that both in one field of database with line breaks. Its working good if I store one textarea value in table field, But I need to store both textarea value in one field.

Example :-

textaera 1)

Hello
text from textarea1

textarea 2)

How are you?
its second textarea text

Output that I need with all line breaks and also between two textarea value :-

Hello
text from textarea1
How are you?
its second textarea text

Upvotes: 1

Views: 668

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Suppose you both values are coming into variables $textarea1 and $textarea2 correspondingly. You can do it like below:-

$combine_data = $textarea1."\n".$textarea2;

OR

$combine_data = $textarea1 . PHP_EOL . $textarea2; and use nl2br($combined) to show it again in text-area //@iainn suggestion

OR

$combine_data = $textarea1 ."<br/>". $textarea2;

Reference Taken :-

add line break between 2 variables

Upvotes: 3

Rasclatt
Rasclatt

Reputation: 12505

As mentioned, if you want to be able to retrieve the blocks separately (for greater flexibility) but store both in one column, you can use serialize():

To store the data:

$data = array('p1'=>$_POST['textarea1'], 'p2'=>$_POST['textarea2']);
$compress = serialize($data);
//insert value $compress into one column in your database

To recall the data:

// Get column from database 
$data = $row['db_column'];
$decompress = unserialize($data);
// Echo to browser using html break and End Of Line constant (for compatibility)
echo implode('<br />'.PHP_EOL,$decompress);

You can also echo each value separately after unserializing:

echo  $decompress['p1'].'<br />'.PHP_EOL.
      $decompress['p2'].'<br />'.PHP_EOL;

By doing it this way, you can recall the data in their respective blocks, that way if you decide to change something later, you still have all the raw data in blocks.

Upvotes: 1

Related Questions