Insert multiple lines from textarea of HTML Form into MySQL database with PHP
Instead of using textfield to input one line of text, we could use textarea of HTML Form for user to input multiple lines. However if we use PHP to insert the text from textarea into the MySQL database with the same method as the textfield, all of the multiple lines will become 1 line and stored into the database. 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”:
<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”:
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:
- Insert values into MySQL database with HTML form and PHP
- Display data from MySQL database with HTML form and PHP
- MD5 – insert an encrypted string or password to the MySQL database with HTML form and PHP
- Delete records from MySQL database with HTML form and PHP
- Merging 2 MySQL tables with PHP – update one table’s field with another table’s field data (both table have one common field)






