Insert multiple lines from textarea of HTML Form into MySQL database with PHP
Instead of using a textfield to input one line of text, we could use textarea for user to input multiple lines. However if we use PHP to insert the text of a textarea into the MySQL database with the same method as the textfield, all of the multiple lines will become 1 line. To solve this issue, we could use a PHP function:
Here is a HTML form contains a textarea which will post to a PHP file “insert.php”:
1 2 3 | <form name="form1" method="post" action="insert.php"> <textarea rows="5" name="area" cols="50" ></textarea> </form> |
textarea:
If we use the same insert method as textfield:
$area = $_POST['area'];
We will insert all of the multiple lines from textarea as 1 single line into the MySQL database, and so we need to use the PHP function:
nl2br()
This function will insert a line break for every new line and so multiple lines from textarea will be able to insert as they are into the MySQL database.
For the file “insert.php”:
First we have to connect to the MySQL database:
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed");
Then we get the multiple lines from the textarea and apply the nl2br() function and store it with a PHP variable:
$area = nl2br($_POST['area']);
Then we create a query for inserting into the MySQL database and the query is stored into a PHP variable:
$query = "INSERT INTO table(field)VALUES('$area')";
We run the query and an if condition is added to check the result:
if(mysql_query($query)){ echo "Inserted into the database";} else{ echo "Fail, please try again";}
All together we have for “insert.php”:
1 2 3 4 5 6 7 8 | mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed"); $area = nl2br($_POST['area']); $query = "INSERT INTO table(field)VALUES('$area')"; if(mysql_query($query)){ echo "Inserted into the database";} else{ echo "Fail, please try again";} |
Similar Posts:
- Change the MySQL database table encoding to UTF8 with PHP
- Merging 2 MySQL tables with PHP – update one table’s field with another table’s field data (both table have one common field)
- Display data from MySQL with PHP
- Insert values into MySQL database with HTML form and PHP
- Display data from MySQL database with HTML form and PHP





Love Kumar said,
Code is very useful for users like me who use PHP sometimes.
Manju said,
Nice code…
Add A Comment