What is the best practice for displaying default values in a PHP form before submission?
When displaying default values in a PHP form before submission, it is important to check if the form has been submitted. If it hasn't, then display the default values. This can be achieved by using the ternary operator to check if the form has been submitted, and if not, display the default values.
<?php
// Define default values
$default_name = "John Doe";
$default_email = "john.doe@example.com";
// Check if form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Form has been submitted, use submitted values
$name = $_POST["name"];
$email = $_POST["email"];
} else {
// Form has not been submitted, use default values
$name = $default_name;
$email = $default_email;
}
?>
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>"><br><br>
<label for="email">Email:</label>
<input type="email" name="email" value="<?php echo $email; ?>"><br><br>
<input type="submit" value="Submit">
</form>
Keywords
Related Questions
- What are the potential advantages and disadvantages of storing data in arrays within PHP source code compared to retrieving data from a MySQL database?
- How can array values be accessed and stored in variables in PHP?
- Are there alternative methods to using the header function in PHP for URL redirection to avoid potential pitfalls like incorrect interpretation by external websites?