I'm absolute beginner in web technologies. I know that my question is very simple, but I don't know how to do it. For example I have a function:
function addNumbers($firstNumber, $secondNumber)
{
echo $firstNumber + $secondNumber;
}
And I have a form:
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
How can I input variables on my text fields and call my function by button pressing with arguments that I've wrote into text fields? For example I write 5 - first textfield, 10 - second textfield, then I click button and I get the result 15 on the same page. EDITED I've tried to do it so:
$num1 = $POST['number1'];
$num2 = $POST['number2'];
addNumbers($num1, $num2);
But it doesn't work, the answer is 0 always.
The variables will be in the $_POST variable.
To parse it to the function you need to do this:
Be sure you check the input, users can add whatever they want in it. For example use is_numeric() function
Also, don't echo inside a function, better return it:
You need to gather the values from the
$_POST
variable and pass them into the function.Be advised, however, that you shouldn't trust user input and thus need to validate and sanitize your input.
Try This.
The "function" you have is server-side. Server-side code runs before and only before data is returned to your browser (typically, displayed as a page, but also could be an ajax request).
The form you have is client-side. This form is rendered by your browser and is not "connected" to your server, but can submit data to the server for processing.
Therefore, to run the function, the following flow has to happen:
Sample PHP script that does all of this:
Please note:
<?php ... ?>
is executed by the server (and in this case,echo
creates the only output from this execution), while everything outside the PHP tags — specifically, the HTML code — is output to the HTTP Response directly.<h1>Result:...
HTML code is inside a PHPif
statement. This means that this line will not be output on the first pass, because there is no$result
.action
has no value, the form submits to the same page (URL) that the browser is already on.You are missing the underscores in
That's all.