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 : "-";)?>'/>
Related
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>
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>
I have got the php, html code.
And I want to post the multiple checkbox values, but this does not work dunno why, I can print count or array, it prints(0), does not matter
the array values is always empty
<form action = 'main.php?w=creatNewTemplate2' method = 'post'>
<input type = 'text' name = 'templateName' maxlength = '30'/><br />
<input type= 'checkbox' name= 'exercises[]' value='A' />A<br />
<input type= 'checkbox' name= 'exercises[]' value='B' />B<br />
<input type = 'submit' value = 'Sukurti'/>
</form>
if($w == "creatNewTemplate2")
{
$d = $_POST['exercises'];
$ddd = count($d);
print_r($_POST);
}
I think this could work for you:
if($w == "creatNewTemplate2")
{
$d = $_POST['exercises'];
$ddd = count($d);
for ($x = 0; $x < $ddd; $x++) {
echo $_POST['exercises'][$x].'<br>';
}
}
If you use same name you need to loop them
This should be work
Or you can change the two checkbox to select multiple
<form action="main.php?w=creatNewTemplate2" method="post">
<input type="text" name="templateName" maxlength="30"/><br/>
<select multiple name="exercices[]">
<option>A</option>
<option>B</option>
</select>
<input type="submit" value="Sukurti"/>
</form>
<?php
if($_GET["w"] == "creatNewTemplate2")
{
foreach ($_POST["exercises"] as $ex) {
echo $ex . '<br>';
}
}
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);
}
so for a class assignment we are using HTML and PHP to make a form that asks a user to input two (2) numbers and to choose between addition, subtraction, multiplication or division form using radio buttons, THEN to input a guess as to what the answer is. Our assignment is to echo out to the user specifying whether or not their answer is correct or not.
The part where I am having troubles is in the "if" and "else" statements. For example, if I choose 1 and 2 as my numbers, guess 3 and choose addition as my method of calculation, I not only get echoed out "Congratulations! You choose the correct answer of 3!" but i also get my else statements from division, subtraction, and multiplication specifying that I did it incorrectly.
Here's my Code:(keep in mind-- the birthday function has yet to be made.)
Also, I'm having difficulties regarding my form validation -- making it so that the user has in fact entered the required fields.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Howdy</title>
</head>
<body>
<h1>PHP_SELF</h1>
<?php
//process the form if the submit button was pressed
if (isset($_POST['submit'])) {
//form validation goes here
/////////////////////////////////////////VARIABLES ARE BEING MADE HERE
//simplify the form variables
//later on we will do this in form validation
//create a variable called firstname and store in it
//the value from the POST array for firstname from the form
$firstname = $_POST['firstname'];
//creating variables for num1 and num2 that user inputed
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
//creating a variable called sum
//this is for when the user chooses to ADD
//num1 and num2
$sum = $num1 + $num2;
//creating a variable called difference
//this is for when the user chooses to SUBTRACT
//num1 and num2
$difference = $num1 - $num2;
//creating a variable called product
//this is for when the user chooses to MULTIPLY
//num1 and num2
$product = $num1 * $num2;
//creating a variable called quotient
//this is for when the user chooses to DIVIDE
//num1 and num2
$quotient = $num1 / $num2;
//creating a variable called guess and store it in the
//value from the POST array for the guess from the form
$guess = $_POST['guess'];
//creating a variable called birthday and store it in the
//value from the POST array for the user's birthday
$birthday = $_POST['birthday'];
if ($sum == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($sum != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $sum.</p>\n";
}
if ($difference == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($difference != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $difference.</p>\n";
}
if ($product == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($product != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $product.</p>\n";
}
if ($quotient == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($quotient != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $quotient.</p>\n";
}
} //end of the isset submit conditional statement
//show the form if it is the user's first time her OR if any of the required forms are missing
if(!isset($_POST ['submit']) OR empty($firstname) OR empty($num1) OR empty($num2)) { ?>
<h2>Please fill out the following: </h2>
<!--FORM BEGINS-->
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="firstname">Please enter your first name: </label>
<input id="firstname" type="text" size="30" name="firstname" value="<?php if(isset($firstname)) echo $firstname; ?>"/><p>
<!--Challenge Dealio-->
<p><label for="Num1">Please enter a number: </label>
<input id="Num1" type="number" size="30" name="num1" value="<?php if(isset($num1)) echo $num1; ?>" /></p>
<p><label for="Num2">Please enter another number: </label>
<input id="Num2" type="number" size="30" name="num2" value="<?php if(isset($num2)) echo $num2; ?>"/><p>
<p>Please choose one of the following: </p>
<p>
<input name="add" id="answer" type="radio" value="add" />Add<br />
<input name="subtract" id="answer" type="radio" value="subtract" />Subtract<br />
<input name="multiply" id="answer" type="radio" value="multiply" />Multiply<br />
<input name="divide" id="answer" type="radio" value="divide" />Divide<br />
</p>
<p><label for="guess">Please put in a guess for the answer: </label>
<input id="guess" type="number" size="30" name="guess" value="<?php if(isset($guess)) echo $guess; ?>"/></p>
<p><label for="birthday">Please enter your birth date: </label>
<input id="birthday" type="date" size="30" name="birthday" value="<?php if(isset($birthday)) echo $birthday; ?>"/></p>
<!--Submit Button-->
<input type="submit" name="submit" value="Enter" />
</form>
<?php
} //end form conditional statement
?>
</body>
</html>
What did I do wrong? And how can I go about fixing this?
First of all al radio buttons should have same name with different value. And in same page you cannot have same id's
<p>
<input name="action" id="add" type="radio" value="add" />Add<br />
<input name="action" id="subtract" type="radio" value="subtract" />Subtract<br />
<input name="action" id="multiply" type="radio" value="multiply" />Multiply<br />
<input name="action" id="divide" type="radio" value="divide" />Divide<br />
</p>
Then in your php to perform selected option,
if($_POST['action'] == "add") {
$result = $num1 + $num2;
} else if($_POST['action'] == "subtract") {
$result = $num1 - $num2;
} else if($_POST['action'] == "multiply") {
$result = $num1 * $num2;
} else if($_POST['action'] == "divide") {
$result = $num1 / $num2;
}
Rename all values to $result.
if($result == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else {
echo "<p>$firstname, you answered incorrectly. The correct answer is $difference.</p>\n";
}
No need to check so many times, take the result to 1 variable, check it only once.
Edit: For birthday part
In View
<select name="year">add options here</select>
<select name="month">add options here</select>
<select name="day">add options here</select>
In PHP,
$month = $_POST['month'];
$year = $_POST['year'];
$day = $_POST['day'];
$date = $year ."-". $month ."-".$day;
$date = date("Y-m-d",strtotime($date));
if(date('m-d') == date('m-d', $date)) {
// today is users birthday. show any message you want here.
}
First of all you cannot have the same ids on your radios. They must be different with the same name.
<p>
<input name="action" id="add" type="radio" value="add" />Add<br />
<input name="action" id="subtract" type="radio" value="subtract" />Subtract<br />
<input name="action" id="multiply" type="radio" value="multiply" />Multiply<br />
<input name="action" id="divide" type="radio" value="divide" />Divide<br />
</p>
Then you are not validating which function the user is choosing via the checkboxes. You are iterating through all the ifand elsewithout filtering which function was chosen.
What I would do is use a Switch Case statement to filter which method of calculation was chosen and then compare if the guess is right. Something like:
switch $answer {
case "add":
//Check if guess is right and echo
break;
case "substract":
//Check if guess is right and echo
break;
case "multiply":
//Check if guess is right and echo
break;
case "divide":
//Check if guess is right and echo
break;
};
If you are not allowed to use the Switch Case Statement then you should first check which answer was marked and then if the guess is right:
if($answer == "add"){
if($sum == $guess){
echo "Congrats";
} else {
echo "error";
}
} else if($answer == "substract"){
if($difference == $guess){
echo "Congrats";
} else {
echo "error";
}
} else if($answer == "multiply"){
if($product == $guess){
echo "Congrats";
} else {
echo "error";
}
} else if($answer == "divide"){
if($quotient == $guess){
echo "Congrats";
} else {
echo "error";
}
}
Hope it helps.