How to create sticky form in php

Sticky form in PHP is a standard HTML form which saves that data have been entered in a form. It’s really helpful for end-user because they don’t need to re-type data into the form if there’s an error while submitting. Let me give you a real example. When you search in google, the search results are displayed below, while texts still appear in the search box

Sticky form in PHP

 

In the previous posts, we have created PHP code to send email as well as display form data, so we will directly create a simple sticky form in PHP in this tutorial. You can see the demo here.

To create this sticky form, we have to follow 2 steps:

  • Step 1: Taking the data sent by the form by using “GET” method: $data= $_GET[“data”];
  • Step 2: Settings that data as a value for input

By default, the form data will be removed after submitting because of this code line: <input name =”data” value=”” />)

We need to change this code to: <input type=”text” name=”data” value=”<?php echo $data; ?>”>

Source code:

At first, put the sticky-form-in-php folder inside \htdocs folder (if you use xampp). In the sticky-form-in-php folder, create index.php file.


<!doctype html>
<html>
<body>
<?php
if (isset($_GET["data"])){
$data= $_GET["data"];
}
else {
$data= "";
}
<form method="GET" >
Enter content: <input type="text" name="data" value="<?php echo $data; ?>">
<button type="submit">Submit</button>
</form>
 
<?php
if (isset($_GET["data"])){
echo  $data = $_GET["data"];
}
?>
</body>
</html>
</code></pre>
 
Let’s discuss about these codes:
<pre><code class="php">
<?php
if (isset($_GET["data"])){
$data= $_GET["data"];
}
else {
$data= "";
}

These piece of codes means that when client add data to the form fields, the system will assign those values to the data variable. If not, the data variable has an empty value.

In case we don’t provide those conditions, the system will display an error if a user leaves an empty field:

 

Sticky form in PHP

The below code line uses for display textbox data that we have taken from the above step:


<input type="text" name="data" value="<?php echo $data; ?>">

The purpose of these codes is displaying data that’s been entered:

<?php
if (isset($_GET["data"])){
echo  $data = $_GET["data"];
}
?>

We hope that you can know how does the sticky form in PHP work through our tutorial. You can download our source code for reference. We also create a video demo so you can fully understand the steps to create a sticky form. If you need to add form validate you could follow the post.

If you’ve any question or recommendation, please do not hesitate to let us know.

Enjoy this blog? Please spread the word :)