MySQL, PHP: Store form textarea value or data to MySQL database table

by Yang Yang on June 6, 2009

in PHP Tips & Tutorials,SQL / MySQL Tips and Tutorials

To send the textarea text value in any HTML forms to the web server and store it into a MySQL table by PHP, you will need to POST the textarea data to a PHP script and then the PHP script would connect to a MySQL database to put the data into one of the tables by inserting a record or updating one.

The HTML:

<textarea rows="10" cols="10" name="bio"></textarea>

Now the visitor has finished typing in his text and clicked the submit button. The data is then transmitted via POST method to a PHP script:

$data = $_POST['bio']; // because the name attribute of the textarea tag is 'bio'
$data = mysql_real_escape_string[$data]; // necessary step before using the data string to prevent SQL injection attacks
mysql_query("INSERT INTO `authors` (`bio`) VALUES ('$data')");

By committing the last SQL query, the bio data entered by the visitor is successfully inserted into the table `authors` as a new record. Other than this, you may also want to use:

UPDATE `authors` SET `bio` = '$data' WHERE ...

To update an existing row with the textarea data instead of inserting a new one.

I think that’s pretty much what the basics look like to put textarea value into a database.

Related Posts

{ 3 comments… read them below or add one }

Mat Landers June 16, 2009 at 2:43 pm

For some reason your use of backticks here prompted me to fix the problem I was having. Thanks!

Reply

Farrukh Shahzad February 11, 2010 at 5:31 pm

If you dnot want to allow the user to enter the html code in the textarea then you can use the PHP function [ strip_tags() ] to remove the thml tags from the text entered.

This function will also remove the javascript.

Reply

Yang Yang February 26, 2010 at 6:00 pm

Nice catch, Farrukh!

Reply

Leave a Comment

Previous post:

Next post: