PHP & Input Text box with default value and Retaining text box value

Retain a text-box value

When validation fails, place the submitted text back into the field only after HTML escaping. This keeps the user's entry while preventing it from becoming markup.

$city = trim($_POST['city'] ?? '');
$safeCity = htmlspecialchars($city, ENT_QUOTES, 'UTF-8');

echo '<input type="text" name="city" value="' . $safeCity . '">';
Here is one text box inside a PHP code area. We will learn here how to retain the text box value after the form is submitted.

Text box within a form

<form method=POST action=pb-text2.php>
<input type=text name=t1>
<input type=submit value=Submit ></form>

Receiving the textbox data

Form is submitting the data by attribute action=pb-text2.php to pb-text2.php file, inside which we will keep this code to receive data and display the same.
<?Php
$t1 = $_POST['t1'] ?? '';
echo htmlspecialchars($t1, ENT_QUOTES, 'UTF-8');
?>

Keeping Default data inside Textbox

We will use default attribute to keep some default data inside input textbox. Source of this data can be a variable or we can display by taking data from a database table. When the page is loaded the data stored in PHP variable will be stored and displayed inside text box as default value. Here is one example
<?Php
$t1="My Data here ";
echo "<input type=text name='t1' value='$t1'>";
?>
Output is here

Redisplaying submitted data in the same form

For a normal validation error, you do not need to send the text through the address bar. Read it from POST, validate it, escape it for HTML, and reuse it in the form value.

Related: HTML forms.

$t1 = trim($_POST['t1'] ?? '');
$safe = htmlspecialchars($t1, ENT_QUOTES, 'UTF-8');

echo "<form method='post' action=''>
<input type='text' name='t1' value='$safe'>
<input type='submit' value='Submit'>
</form>";

Demo of the textbox script

Demo of the textbox script

Example : Updating data from database

You are asked to update your address, the site will collect your present address from a database table and show it to you as default data inside a textbox. You can change the data and submit to update the table with your new address.

Name

Address 1

Address 2

City

State

Country

Zip


Sitemap Form Form post back data
Managing listbox in a Form using PHP Checkbox in PHP Radio buttons
PHP sticky form using textbox


Subscribe to our YouTube Channel here



plus2net.com







23232323

21-09-2018

vbvb




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer