How to Remove a Variable on a PHP on Submit
Combining a scripting language such as PHP with Web pages adds interactivity to websites. Users can manage content in a control panel or purchase goods with the help of some HTML Web forms and PHP, along with other code. If you want to do something like remove a variable when the user clicks the "Submit" button, you need to use PHP to check the form first and then use the "unset()" function on the variable. This is just one example of PHP-driven interactivity.
Instructions
-
-
1
Open the PHP file for the Web page you need to edit in Notepad or a code editor. This PHP file should already contain an HTML form with a "Submit" button. Check that the method of the form is "post" and the action of the form matches the name of the file containing the form:
<form method="post" action="myform.php">
-
2
Add a pair of PHP delimeter tags below the closing "</form>" tag and begin writing an "If-Then" conditional statement:
<?php
if () {
}
?>
-
-
3
Use the "isset()" function inside the parantheses of your "If-Then" statement to check if "$_POST['submit']" contains a value:
<?php
if (isset($_POST['submit'])) {
}
?>
In the above code, "$_POST" is an array variable that holds the values of every field and button in your HTML form. Use the name of the "Submit" button to get its value, in this case "submit."
-
4
Use the "unset()" function within your "If-Then" statement to unset the variable you want to remove:
unset($myvar);
The variable will no longer contain any value.
-
5
Put your "unset($myvar);" code inside a new "If-Then" statement to check if the variable exists and holds a value:
if (isset($myvar)) {
unset($myvar);
}
This code will protect your Web page from errors when the user clicks the "Submit" button mutliple times. If there is no "$myvar" variable, then the PHP code will not run the "unset()" function.
-
1