I'm creating a program where the user enters two numbers and on the submit button it will calculate and display the fibonacci sequence. When trying to get my input values to be stored in $n1
and $n2
I get an error. Is there a more effective way to get input by doing something other then a $_POST
?
This is the form:
<div id="container">
<h2>Fibonacci Example</h2>
<p id="display"></p>
<form action="fibonacciDisplay.php" method="post">
<label>First Number:</label> <input type="text" name="n1"><br>
<label>Second Number:</label> <input type="text" name="n2"><br>
<input type="submit" name="calculate" class="btnSubmit">
</form>
</div>
This is my function:
//variables
$n1 = $_POST['Num1'];
$n2 = $_POST['Num2'];
//method to check numbers
function checkFibo($n1 = 0, $n2 = 0) {
if ($n1 != 0 && $n2 != 1) {
if ($n2 < $n1) {
echo "Your second number must be greater than the first. Try again";
$output = "";
} else if ($n1 < $n2 || $n2 < 0) {
echo "Please enter only positive numbers";
} else if (!(is_numeric($n1)) || !(is_numeric($n2))) {
echo "Please only enter positive numbers";
$output = "";
} else {
echo "The result of your request is shown below.";
$output = $z->getFibo($n1, $n2);
}
} else {
echo "Please enter values below";
$output = "";
}
return $output;
}
// Method to calculate fibonacci
function getFibo($n1 = 0, $n2 = 0) {
$max = $n2 * 100;
while ($z <= 0) {
$z = $n1 + $n2;
$output .= ($z."<br />");
$n1 = $n2;
$n2 = $z;
}
return $output;
}
Change this<label>First Number:</label> <input type="text" name="n1"><br> <label>Second Number:</label> <input type="text" name="n2"><br>
to this:<label>First Number:</label> <input type="text" name="Num1"><br> <label>Second Number:</label> <input type="text" name="Num2"><br>
Because you try to get fields $n1 = $_POST['Num1'];$n2 = $_POST['Num2'];
in your backend script.
About second question, you can use GET
requests instead of POST
more here, if you'd like to make it more modern, look at ajax requests.
Your PHP code is incorrect on grabbing the values from post. Num1 and Num2 doesn't exist in your html code, you declared them as n1 and n2. Hence you should do $_POST['n1'] and $_POST['n2']
Your html:
<label>First Number:</label> <input type="text" name="n1"><br>
<label>Second Number:</label> <input type="text" name="n2"><br>
Your current PHP code:
$n1 = $_POST['Num1'];
$n2 = $_POST['Num2'];
Your PHP should be:
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];