How can I echo a statement from a form? - php

I'm a student doing a challenge where I would have to make a Calculator-type form where you can input two values and click an operation. It's a simple concept using only 4 operations.
I was able to make the format of the form: title, input text and buttons. But I can't find a way to take the input information and manipulating the information. My initial goal was to take the two values and adding/subtracting/multiplying/dividing the values and printing the statement above.
For example:
1 + 2 = 3 //statement printed above
First Value: 1
Second Value: 2 //insert values
+ - * / //click operation buttons
Any suggestions?
<!DOCTYPE HTML>
<?php
print_r($_POST);
if ( isset($_POST["+"]) ) {
$sum = $var1 + $var2;
echo "$var1 + $var2 = $sum";
}
elseif( isset($_POST["-"]) ) {
$sum = $var1 - $var2;
echo "$var1 - $var2 = $sum";
}
elseif ( isset($_POST["*"]) ) {
$sum = $var1 * $var2;
echo "$var1 * $var2 = $sum";
}
elseif ( isset($_POST["/"]) ) {
$sum = $var1 / $var2;
echo "$var1 / $var2 = $sum";
}
?>
<html>
<body>
<form action="" method="POST">
First Value: <input type="text" name="First Value"><br><br>
Second Value: <input type="text" name="Second Value"><br><br>
Operations: <button type="submit" name "+">+</button>
<button type="submit" name "-">-</button>
<button type="submit" name "*">*</button>
<button type="submit" name "/">/</button>
</form>
</body>
</html>

This seems to fix the errors I mentioned in comments
<!DOCTYPE HTML>
<html>
<body>
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
if ( isset($_POST["+"]) ) {
$sum = $_POST['var1'] + $_POST['var2'];
echo "$_POST[var1] + $_POST[var2] = $sum";
}
elseif( isset($_POST["-"]) ) {
$sum = $_POST['var1'] - $_POST['var2'];
echo "$_POST[var1] - $_POST[var2] = $sum";
}
elseif ( isset($_POST["*"]) ) {
$sum = $_POST['var1'] * $_POST['var2'];
echo "$_POST[var1] * $_POST[var2] = $sum";
}
elseif ( isset($_POST["/"]) ) {
$sum = $_POST['var1'] / $_POST['var2'];
echo "$_POST[var1] / $_POST[var2] = $sum";
}
}
?>
<form action="" method="POST">
First Value: <input type="text" name="var1"><br><br>
Second Value: <input type="text" name="var2"><br><br>
Operations: <button type="submit" name="+">+</button>
<button type="submit" name="-">-</button>
<button type="submit" name="*">*</button>
<button type="submit" name="/">/</button>
</form>
</body>
</html>

I don't know if it's the right way to do things but you can use jquery in the script section to do so, let's say you have this form
<form id="target" action="destination.html">
<input type="text" value="Hello there">
<input type="submit" value="Go">
</form>
so on the submit you do the math
$( "#target" ).submit(function( event ) {
//do the math//
document.write(//your answer//);
event.preventDefault();
});

<?php
$first_num = $_POST['first_num'];
$second_num = $_POST['second_num'];
$operator = $_POST['operator'];
$result = '';
if (is_numeric($first_num) && is_numeric($second_num)) {
switch ($operator) {
case "Add":
$result = $first_num + $second_num;
break;
case "Subtract":
$result = $first_num - $second_num;
break;
case "Multiply":
$result = $first_num * $second_num;
break;
case "Divide":
$result = $first_num / $second_num;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="page-wrap">
<h1>Simple Calculator Program</h1>
<form action="" method="post" id="quiz-form">
<p>
<label>First Number</label>
<input type="number" name="first_num" id="first_num" required="required" value="<?php echo $first_num; ?>" />
</p>
<p>
<label>Second Number</label>
<input type="number" name="second_num" id="second_num" required="required" value="<?php echo $second_num; ?>" />
</p>
<p>
<label>Result</label>
<input readonly="readonly" name="result" value="<?php echo $result; ?>">
</p>
<input type="submit" name="operator" value="Add" />
<input type="submit" name="operator" value="Subtract" />
<input type="submit" name="operator" value="Multiply" />
<input type="submit" name="operator" value="Divide" />
</form>
</div>
</body>
</html>

Related

how to use the single input received multiple times in php

for example, I receive two inputs value1 and value2 and I want this input for different functions. Like addition, subtraction and multiplication.
my code
<?php
$x = $_POST['fnum'];
$y = $_POST['snum'];
if (isset($_POST['add'])) {
$sum = $x + $y;
echo "Result:<input type='text' value='$sum'/>";
}
if (isset($_POST['sub'])) {
$sub = $x - $y;
echo "Result:<input type='text' value='$sub'/>";
}
if (isset($_POST['mul'])) {
$mul = $x * $y;
echo "Result:<input type='text' value='$mul'/>";
}
<body>
<form method="post">
Enter first number <input type="text" name="fnum" />
<hr />
Enter second number <input type="text" name="snum" />
<hr />
<input type="submit" name="add" value="ADD" />
<input type="submit" name="sub" value="Subtract" />
<input type="submit" name="mul" value="Multiply" />
</form>
</body>
In this it is asking me to feed input for each operation separately
Good, Just use the posted value in your form input like -
Enter first number <input type="text" name="fnum" value="<?php echo #$_POST['fnum'];?>"/><hr/>
Enter second number <input type="text" name="snum" value="<?php echo #$_POST['snum'];?>"/><hr/>
So that user don't need to put the same value again and when press the other buttons the form will automatically submit with the previous values.
Note: Remember, you need to check all the posted value is set or not and use proper conditions of POST method. Have a look at the given example of your problem as solution, I give it here to give you a proper guide.
Example:
<?php
$x = 0;
$y = 0;
if(isset($_POST['submit'])) {
$x = $_POST['fnum'];
$y = $_POST['snum'];
$operator = "";
if($_POST['submit'] == 'ADD') {
$operator = "+";
} elseif($_POST['submit'] == 'Subtract') {
$operator = "-";
} elseif($_POST['submit'] == 'Multiply') {
$operator = "*";
}
$result = $x . $operator . $y;
}?>
Your form will be-
<form method="post">
Enter first number <input type="text" name="fnum" value="<?php echo $x;?>"/><hr/>
Enter second number <input type="text" name="snum" value="<?php echo $y;?>"/><hr/>
<input type="submit" name="submit" value="ADD"/>
<input type="submit" name="submit" value="Subtract"/>
<input type="submit" name="submit" value="Multiply"/>
</form>
Result:
<input type='text' value='<?php echo (isset($result) ? $result : "-";)?>'/>

PHP calculator not returning value

Hi im very new to this stuff. My PHP calculator returns nothing when I hit calculate, when I upload this file to my 000webhost site. I don't have the website up right now but here is my code.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="get" action="#">
Enter the First Number <input type="text" name="number1"> <br><br>
Enter the Second Number <input type="text" name="number2"><br><br>
Choose the operation
Addition <input type="radio" name="op" value="add" checked>
Subtraction <input type="radio" name="op" value="sub">
Multiplication <input type="radio" name="op" value="mul">
Division<input type="radio" name="op" value="div"><br><br>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
<?php
if ( $op == "add" ) {
echo "$number1 + $number2 = ";
echo $number1 + $number2;
}
if ( $op == "sub" ) {
echo "$number1 - $number2 = ";
echo $number1 - $number2;
}
if ( $op == "mul" ) {
echo "$number1 * $number2 = ";
echo $number1 * $number2;
}
if ( $op == "div" ) {
echo "$number1 / $number2 = ";
echo $number1 / $number2;
}
?>
<html>
When I hit calculate nothing happens and the link gets a question mark in it. Please help.
You need to use $_GET for accessing input value from get form request
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="get" >
Enter the First Number <input type="text" name="number1"> <br><br>
Enter the Second Number <input type="text" name="number2"><br><br>
Choose the operation
<br>
<input type="radio" name="op" value="add" checked>Addition<br>
<input type="radio" name="op" value="sub">Subtraction<br>
<input type="radio" name="op" value="mul">Multiplication<br>
<input type="radio" name="op" value="div">Division<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset( $_GET['number1']) && isset( $_GET['number2']) && isset( $_GET['op'])) {
$number1 = $_GET['number1'];
$number2 = $_GET['number2'];
$op = $_GET['op'];
if ($op == "add") {
echo "$number1 + $number2 = ";
echo $number1 + $number2;
}
if ($op == "sub") {
echo "$number1 - $number2 = ";
echo $number1 - $number2;
}
if ($op == "mul") {
echo "$number1 * $number2 = ";
echo $number1 * $number2;
}
if ($op == "div") {
echo "$number1 / $number2 = ";
echo $number1 / $number2;
}
}
?>
<html>

PHP practice function ($result) can't be called

I am doing PHP practice and I am stuck on this part.
My problem is when I do simple math like 1+1 or 1/1 etc. The $result won't display. I am confused about which part of my code is causing the problem. Please enlighten me on my mistakes
Thank you.
<?php
$first_num = $_POST['first_num'];
$second_num = $_POST['second_num'];
$operator = $_POST['operator'];
$result = '';
function cal_result($first_num,$second_num,$operator){
if (is_numeric($first_num) && is_numeric($second_num)) {
switch ($operator) {
case "Add":
$result = $first_num + $second_num;
break;
case "Subtract":
$result = $first_num - $second_num;
break;
case "Multiply":
$result = $first_num * $second_num;
break;
case "Divide":
$result = $first_num / $second_num;
}
return $result;
}
}
?>
<form action="simple_calculator.php" method="post" id="quiz-form">
<p>
<input type="number" name="first_num" id="first_num" required="required" value="<?php cal_result($first_num,$second_num,$operator); ?>" /> <b>First Number</b>
</p>
<p>
<input type="number" name="second_num" id="second_num" required="required" value="<?php cal_result($first_num,$second_num,$operator); ?>" /> <b>Second Number</b>
</p>
<p>
<input readonly="readonly" name="result" value="<?php echo $result; ?>"> <b>Result</b>
</p>
<input type="submit" name="operator" value="Add" />
<input type="submit" name="operator" value="Subtract" />
<input type="submit" name="operator" value="Multiply" />
<input type="submit" name="operator" value="Divide" />
</form>
I think you are confused by the short open tag
if I print
<?=$result;?>
or
<?=cal_result($first_num,$second_num,$operator);?>
this is the same thing like
<?php echo $result;?>
or
<?php echo cal_result($first_num,$second_num,$operator);?>
If you call a function that ´returns´ values, and you want to use them , you must also print them out...
also check out global variables. If you want to use $result outside the function scope you must declare it a global variable.
<?php
$result = '';
$first_num = 0;
$second_num = 0;
$ops = array( "+",
"-",
"×", // HTML : × , ASCII CODE : 158
"÷"); // HTML : ÷ , ASCII CODE : 246
// checking if the first number is what he should be
if ( isset($_POST['first_num']) &&
!empty($_POST['first_num']) &&
is_numeric($_POST['first_num']) )
{
$first_num = $_POST['first_num'];
}
// checking if the second number is what he should be
if ( isset($_POST['second_num']) &&
!empty($_POST['second_num']) &&
is_numeric($_POST['second_num']) )
{
$second_num = $_POST['first_num'];
}
function cal_result($first_num,$second_num,$operator){
// optionally you can assign global
global $result;
// here we prevent injection by acceptint only operators from the ops array
if (isset($_GET['operator']) && in_array($_GET['operator'],$ops)) {
switch ($_GET['operator']) {
case $ops[0]: // first element of array ops is Add
$result = $first_num + $second_num;
// remember this function is just returning the $result
// variable it is not printing it, you will have to assiging
// the function to a variable if you want to use the
return $result;
break;
case $ops[1]: // second element of array ops is Subtract
$result = $first_num - $second_num;
return $result;
break;
case $ops[2]: // third element of array ops is Multiply
$result = $first_num * $second_num;
return $result;
break;
case $ops[3]: // fourth element of array ops is Divide
// divide by zero problem
if($second_num !== 0){
$result = $first_num / $second_num;
}else{
$result = "Err: Div By Zero";
}
return $result;
break;
}
}
}
}
?>
<p>
<!--// now you have 2 possibilities : //-->
<!--// first you can call the global variable $result //-->
<label for="quiz-form"><?=$result;?></label>
<!--// the second possibility is to call the function //-->
<label for="quiz-form"><?=cal_result($first_num,$second_num,$operator);?></label>
<b>Result</b>
</p>
<!-- for post you should also set enctype for security reasons -->
<form action="simple_calculator.php"
method="post"
id="quiz-form"
enctype="application/x-www-form-urlencoded">
<p>
<input type="number"
name="first_num"
id="first_num"
required="required"
value="<?=$first_num;?>" />
<b>First Number</b>
</p>
<p>
<input type="number"
name="second_num"
id="second_num"
required="required"
value="<?=$second_num;?>" />
<b>Second Number</b>
</p>
<input type="submit" name="operator" value="+" alt="Add" />
<input type="submit" name="operator" value="-" alt="Subtract" />
<input type="submit" name="operator" value="×" alt="Multiply" />
<input type="submit" name="operator" value="÷" alt="Divide" />
</form>

Php and HTML forms - random values in input fields

I write a conversion from celsius to fahrenheit and vice versa. The problem is that in the form fields now random values ​​are displayed to me. How to convert this code so that after entering the value, the converted value in the second field appears in the first field?
Is it possible to use only php at all?
if(isset($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
}
if(isset($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $fah; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $cel; ?>" name="cel">
<input type="submit" value="Calc">
</form>
I want the value entered in the first field to be shown in the second transformed.
You can do all php if you post back to itself. If the page with the input is calc.php
Add an else to set the value to empty string.
if(isset($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
} else {
$cel = '';
}
if(isset($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
} else {
$fah = '';
}
Try something like this
$cel="";
$fah="";
if(isset($_POST['fah']) && !empty($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
}
if(isset($_POST['cel']) && !empty($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
}
You can try this example:
$celValue = $_POST['cel'];
$fahValue = $_POST['fah'];
if( ! empty($fahValue)){
$celValue = fahrenheitToCelcius($_POST['fah']);
}
if( ! empty($celValue)){
$fahValue = celciusToFahrenheit($_POST['cel']);
}
function celciusToFahrenheit($cel) {
return ($cel - 32) * 1.8;
}
function fahrenheitToCelcius($fah) {
return ($fah + 32) / 1.8;
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $celValue; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $fahValue; ?>" name="cel">
<input type="submit" value="Calc">
</form>
Since both the variables give isset() true so we can have something like this
if(isset($_POST['fah']) && isset($_POST['cel'])) {
//if cel is not empty
if(!empty($_POST['cel'])) {
$cel = $_POST['cel'];
$fah=($cel-32)*1.8;
} else if(!empty($_POST['fah']){
$fah = $_POST['fah'];
$cel = ($fah+32)/1.8;
}
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $fah; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $cel; ?>" name="cel">
<input type="submit" value="Calc">
</form>
You just missing set default values that will overwrite if other post value exist, and else if to load only one parameter so other will be empty
<?php
$cel = "";
$fah = "";
if(isset($_POST['fah'])){
$cel=($_POST['fah']+32)/1.8;
}elseif(isset($_POST['cel'])){
$fah=($_POST['cel']-32)*1.8;
}
?>
<html>
<body>
<form method="post" action="calc.php">
Fahrenheit: <input id="inFah" type="text" placeholder="Fahrenheit" value="<?php echo $fah; ?>" name="fah">
Celcius: <input id="inCel" type="text" placeholder="Celcius" value="<?php echo $cel; ?>" name="cel">
<input type="submit" value="Calc">
</form>

Group Arrays By Another Array?

I'm trying to sort one array by another array. Both these arrays get their content from a form.
Here's my form code:
<form method="post" action="">
<div class="groupcontainer">
<br/><label>Group One:</label><br/>
<input type="text" name="groupname[]" value="groupone" /><br/>
<br/><label>Variable Group One:</label><br/>
<input type="text" name="variable[]" value="variableone" />
<input type="text" name="variable[]" value="variabletwo" />
</div>
<br/>
<div class="groupcontainer">
<br/><label>Group Two:</label><br/>
<input type="text" name="groupname[]" value="grouptwo" /><br/>
<br/><label>Variable Group Two:</label><br/>
<input type="text" name="variable[]" value="variablethree" />
<input type="text" name="variable[]" value="variablefour" />
</div>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
Here's the PHP code:
<?php
if (!$_POST['submit'] == "") {
foreach($_POST['groupname'] as $groupname) {
$groupnum = 1;
foreach($_POST['variable'] as $variable) {
print "$".$groupname.$groupnum." = '".$variable."';<br/>";
$groupnum++;
}
print "$".$groupname." = array(";
for ($arrnum = 1; $arrnum <= count($_POST['variable']); $arrnum++) {
print "$".$groupname.$arrnum.", ";
}
print ");<br/><br/>";
}
}
?>
This is the result I get when I submit the form:
$groupone1 = '$variableone';
$groupone2 = '$variabletwo';
$groupone3 = '$variablethree';
$groupone4 = '$variablefour';
$groupone = array($groupone1, $groupone2, $groupone3, $groupone4, )
$grouptwo1 = '$variableone';
$grouptwo2 = '$variabletwo';
$grouptwo3 = '$variablethree';
$grouptwo4 = '$variablefour';
$grouptwo = array($grouptwo1, $grouptwo2, $grouptwo3, $grouptwo4, )
This is the result that I actually want:
$groupone1 = '$variableone';
$groupone2 = '$variabletwo';
$groupone = array($groupone1, $groupone2)
$grouptwo1 = '$variablethree';
$grouptwo2 = '$variablefour';
$grouptwo = array($grouptwo1, $grouptwo2)
The whole thing needs to be dynamic since I want to add as many groups and variables as I want.
I've been searching for an answer for days and already asked two people who didn't know an answer. Maybe you guys can help. Thanks!
Update:
Just to clarify a few points:
So basically I want to be able to add as many input forms as I want (I use jQuery for that) to create as many groups and variables as I want, for example like this:
$groupwuteva1 = 'hello';
$groupwuteva2 = 'bye':
$randomname1 = 'green';
$randomname2 = 'blue';
$randomname3 = 'red';
$blabla1 = 'abc';
$blabla2 = 'xyz';
$blabla3 = '123';
$blabla4 = 'bla';
Whatever I use as groupname will be used in array one, e.g. I call a group "Colors" and the variables I put into the form for that group are "blue", "red" and "green". Then I would get this code:
$colors1 = 'green';
$colors2 = 'blue';
$colors3 = 'red';
I hope this clairfies some questions. And thanks a ton for all responses so far!
You can take the group name as a container to store all associated variable values in it. And later, use variable variables and implode() function to process your html form.
HTML
<form method="post" action="">
<div class="groupcontainer">
<br/><label>Groupe One:</label><br/>
<input type="text" name="groupname[]" value="groupone" /><br/>
<br/><label>Variable Group One:</label><br/>
<input type="text" name="groupone[]" value="variableone" />
<input type="text" name="groupone[]" value="variabletwo" />
</div>
<br/>
<div class="groupcontainer">
<br/><label>Groupe Two:</label><br/>
<input type="text" name="groupname[]" value="grouptwo" /><br/>
<br/><label>Variable Group One:</label><br/>
<input type="text" name="grouptwo[]" value="variablethree" />
<input type="text" name="grouptwo[]" value="variablefour" />
</div>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
PHP
if(isset($_POST['submit'])){
foreach($_POST['groupname'] as $value){
$arr = array();
$i = 1;
foreach($_POST[$value] as $v){
$var = $value . $i;
$$var = $v;
echo $var . " = " . $$var . "<br />";
$arr[] = $$var;
++$i;
}
$output = $value . " = array(" . implode(",", $arr) . ")";
echo $output . "<br /><br />";
}
}
Output:
groupone1 = variableone
groupone2 = variabletwo
groupone = array(variableone,variabletwo)
grouptwo1 = variablethree
grouptwo2 = variablefour
grouptwo = array(variablethree,variablefour)
try this form:
<form method="post" action="">
<?php foreach(array('groupone', 'grouptwo') as $num):?>
<div class="groupcontainer">
<br/><label>Groupe <?php echo $num;?>:</label><br/>
<input type="text" name="groupname[]" value="<?php echo $num;?>" /><br/>
<br/><label>Variable Group <?php echo $num;?>:</label><br/>
<input type="text" name="variable[<?php echo $num;?>][]" value="<?php echo uniqid();?>" />
<input type="text" name="variable[<?php echo $num;?>][]" value="<?php echo uniqid();?>" />
</div>
<br/>
<?php endforeach;?>
<input type="submit" name="submit" value="Submit" />
</form>
and code:
if ($_POST) {
foreach($_POST['groupname'] as $groupname) {
$$groupname = array();
foreach($_POST['variable'][$groupname] as $variable) {
${$groupname}[] = $variable;
}
}
var_dump($groupone);
var_dump($grouptwo);
}

Categories