How can PHP be used to calculate values based on user input from a form?
To calculate values based on user input from a form in PHP, you can use the $_POST superglobal to retrieve the user input values from the form fields. Then, perform the necessary calculations using these input values and display the result to the user.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$result = $num1 + $num2; // Perform the calculation
echo "The result is: " . $result; // Display the result to the user
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="num1" placeholder="Enter number 1">
<input type="text" name="num2" placeholder="Enter number 2">
<button type="submit">Calculate</button>
</form>
Keywords
Related Questions
- What potential pitfalls should be avoided when incrementing IDs for user display purposes in PHP?
- What best practices should be followed when selecting databases with multiple MySQL connections in PHP?
- What potential issues can arise when trying to pass large amounts of data using the GET method in PHP?