This post will demonstrate how to use PHP to save textarea values in a database.
When users input information into a textarea on our website, it's essential to store that data efficiently. Saving and displaying lengthy content, such as user comments and feedback, in a database is a fundamental component of our PHP web project.
This is a common task that beginner developers face, but don't worry, the article will walk you through the steps to complete this work.
Create New ProjectÂ
Check the directory structure of the project. This project is configured within the xampp/htdocs folder.
xampp/
+-- htdocs/
+-- Save-Textarea-Value-Database-PHP/
+-- dbconfig.php
+-- index.php
if you have WampServer installed configure this project inside wamp/www folder.
wamp/
+-- www/
+-- Save-Textarea-Value-Database-PHP/
+-- dbconfig.php
+-- index.php
Creating a Database Table
To rapidly generate a user table, choose your database and execute the SQL command below.
CREATE TABLE tbl_user (
id int,
user_address varchar(255)
);
Connect the Database
Make dbconfig.php a new PHP file. This contains the code that connects to a MySQL database using the PDO extension.Â
Since the database connection lets you use the same connection code for different files, this file has been created separately.
<?php
$db_host="localhost";
$db_user="root";
$db_password="";
$db_name="textarea_db";
try
{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
Create an HTML Form with a textarea Element:
To collect textarea input, we developed a new PHP file called index.php.
I made a simple HTML form with a <textarea> field and a submit button in this file.
To communicate the textarea value to the server, we set the form method to POST.
The two variables $errorMsg and $insertMsg, which are set using the isset() function, that are available after closing the </form>. The PHP insert scripts that we will see in the next sections are where these variables come from.
Should there be a problem with the PHP insert code, the $errorMsg will display an appropriate error message.Â
If the PHP insert code is executed correctly, the $insertMsg variable will display the data insert successfully message.
<form method="post" class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label">Address</label>
<div class="col-sm-6">
<textarea name="txt_address" class="form-control" rows="5" placeholder="enter your address"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6 m-t-15">
<input type="submit" name="btn_save" value="Save" class="btn btn-success btn-lg btn-block" >
</div>
</div>
</form>
<?php
if(isset($errorMsg))
{
?>
<div class="alert alert-danger alert-dismissible">
<strong>WRONG ! <?php echo $errorMsg; ?></strong>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php
}
if(isset($insertMsg))
{
?>
<div class="alert alert-success alert-dismissible">
<strong>SUCCESS ! <?php echo $insertMsg; ?></strong>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php
}
?>
Look at the below form shows UI of this type:
Store textarea value in Database
In this code, we implement the PHP script that handles our form-submitted requests and stores the textarea value in the database.Â
<?php
require_once "dbconfig.php";
if(isset($_REQUEST['btn_save']))
{
$address = $_REQUEST['txt_address']; //get textarea value "txt_address"
if(empty($address)){
$errorMsg="Please Enter Your Address";
}
else
{
try
{
if(!isset($errorMsg))
{
$insert_stmt=$db->prepare('INSERT INTO tbl_user(user_address) VALUES(:uadd)'); //sql insert query
$insert_stmt->bindParam(':uadd',$address); //bind insert query parameter of :uadd
if($insert_stmt->execute())
{
$insertMsg="textarea value save successfully in database........"; //run query success message
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
Explanation:
Row no 3 -Â I included the dbconfig.php file, which has the database connection code, using the require_once keyword.
require_once "dbconfig.php";
Row no 5 -Â The value "btn_save" for the submit button name attribute value, which is set by the isset() function, is retrieved using the $_REQUEST[] super global array variable.
if(isset($_REQUEST['btn_save']))
{
Row no 7 -Â We obtain the textarea name attribute value "txt_address" using the $_REQUEST[ ] array variable and assign it to the $address variable.Â
$address = $_REQUEST['txt_address']; //get textarea value "txt_address"
Row no 9 -Â This condition uses the empty() function to verify that the textarea value is not null.
if(empty($address)){
$errorMsg="Please Enter Your Address";
}
Row no 12 to 31 -Â We open the try-catch block inside the else condition. The code in the try-catch section will execute if there is no error.
if(!isset($errorMsg)) { -Â This condition verifies that there isn't an error message in the $errorMsg variable before continuing with the function.
This condition looks for an error message in the $errorMsg variable; if it finds none, the code continues.
The SQL insert query is applied in the prepare() function using the $db object of the database connection, and the statement is allocated to the $insert_stmt variable.
The message "textarea value inserted successfully" is displayed in the $insertMsg variable if the $insert_stmt statement is executed by the execute() function.
else
{
try
{
if(!isset($errorMsg))
{
$insert_stmt=$db->prepare('INSERT INTO tbl_user(user_address) VALUES(:uadd)'); //sql insert query
$insert_stmt->bindParam(':uadd',$address); //bind insert query parameter of :uadd
if($insert_stmt->execute())
{
$insertMsg="textarea value save successfully in database........"; //run query success message
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Test the Application
We tested this application on our browser.
See the illustration below. We inserted a textarea value into the database, and the code afterward showed a successful message.
Additionally, we attempted to enter the textarea empty value into the database; however, the code displayed an appropriate error message.
Download Codes
No comments:
Post a Comment