Insert multiple lines from textarea of HTML Form into MySQL database with PHP

Posted by Shek on October 4, 2009 under PHP | 2 Comments to Read | Total View: 3,194 views

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:

VN:F [1.9.13_1145]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.13_1145]
Rating: +1 (from 1 vote)
Insert multiple lines from textarea of HTML Form into MySQL database with PHP, 10.0 out of 10 based on 1 rating
  • Love Kumar said,

    Code is very useful for users like me who use PHP sometimes.

    VA:F [1.9.13_1145]
    Rating: 4.0/5 (1 vote cast)
    VA:F [1.9.13_1145]
    Rating: +1 (from 1 vote)
  • Manju said,

    Nice code…

    VA:F [1.9.13_1145]
    Rating: 5.0/5 (1 vote cast)
    VA:F [1.9.13_1145]
    Rating: +2 (from 2 votes)

Add A Comment

*