Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

How do I enter a textarea into my database and include line breaks?

I've got a tbody of text in a textfield that has several line breaks in it. How do I write an INSERT statement that maintains those line breaks? What do I have to do to "$text" variable to ensure that the integrity of line breaks and paragraphs is inserted correctly?
Avatar of bui_trung_hieu
bui_trung_hieu
Flag of Viet Nam image

You can use javascript to replace line-break characters /\n/ in textarea with HTML line-break tag <br /> before submit form like the example below

Hope this helps.

<form action="" name="theForm" method="post">
<div>
	<p><textarea name="txt"></textarea></p>
    <p><input type="hidden" name="hid" value="" />
	<p><input type="button" value="Submit" onClick="javascript: submit_it()"> </p>
</div>
</form>
<script type="text/javascript">
function submit_it(){
	var a;
	a = document.theForm.txt.value.replace(/\n/g, '<br />');
	document.theForm.hid.value = a;
	document.theForm.submit();
}
</script>

Open in new window

Before you enter your textarea var into database just do a string replace..

here's an example..

 
str_replace("\n","<br>",$textarea);
 
$sql = "insert into table ('$textarea')";

Open in new window

Sorry..
$textarea = str_replace("\n","<br>",$textarea);
 
$sql = "insert into table ('$textarea')";

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of DarkFish
DarkFish

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial