Only ahow error message when error occurs - php

I am creating a calculator on the web to challenge my ability to think an challenge my creative edge and i got the basics down it works but the issue i am having is the error displaying whem there is no error is just displays when the page loads and then displays the value when the calculator is used can someone please help?
<?php
$value1 = $_POST['value1'];
$symbol = $_POST['operator'];
$value2 = $_POST['value2'];
$nulr = "nulrl";
if($nulr === "nulrl"){
if($symbol === "+"){
$output = $value1 + $value2;
} elseif($symbol === "-"){
$output = $value1 - $value2;
} elseif($symbol === "/"){
$output = $value1 / $value2;
} elseif($symbol === "*"){
$output = $value1 * $value2;
} else{
$output = "Error could not perform operation";
}
}
echo $output;
?>
EDIT
Here is my html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>The Goal</h1>
<p>Through my studies of coding languages i have come to realize that just about every coding langauage no matter how different the syntax can handle user input and variables and produce and output. With this being said i wanna make an interactive calculator for each coding language and then advance on each one and see which language can produce the best calculator!</p>
<main>
<h2>PHP Calculator</h2>
<form method="post">
<input type="number" name="value1" value="value1" class="number-box">
<br>
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<br>
<input type ="number" name="value2" value="value2" class="number-box">
<br>
<input type ="submit" name="submit" class="submit-button">
</form>
<?include("calculator.php")?>
<footer>
<h3>Comment Box</h3>
<form method="post" action="comment.php">
<input type="text" value="name" name="name">
<br>
<textarea name="comment">Comments</textarea>
<input type="submit" name="submit" class="submit-button">
</form>
<?php
echo file_get_contents("comments.txt");
?>
</footer>
</main>
</header>
EDIT:
Still have not recieved any correct answers

The simplest way:
<?php
if(isset($_POST['value1']){
//.......
else{
$output = '';
echo "Error, could not perform operation";
}
}
echo $output;
}
?>

Put your code like this:
$http_post = ($_SERVER['REQUEST_METHOD'] == 'POST') ;
if($http_post)
{
$value1 = $_POST['value1'];
$symbol = $_POST['operator'];
$value2 = $_POST['value2'];
$nulr = "nulrl";
if($nulr === "nulrl"){
if($symbol === "+"){
$output = $value1 + $value2;
} elseif($symbol === "-"){
$output = $value1 - $value2;
} elseif($symbol === "/"){
$output = $value1 / $value2;
} elseif($symbol === "*"){
$output = $value1 * $value2;
}
else
{
$output = "Error could not perform operation";
}
}
echo (!empty($output)) ? $output : '';
If any errors occur it will appear only after post.

Related

A swap button for a currency converter

I have a problem with this code, what happens is that I want to create a swap button to change two selectbox of place, such as the google currency converter and those of the internet, I would greatly appreciate your help if you taught me how to do it, the code I did with php. And an apology if I said something wrong I am a beginner in this world
// Output text
$out = $ans = $txtAmount =
// txtSelectBox1 selection
$selA0 = $selA1 = $selA2 = $selA3 =
// txtSelectBox2 selection
$selB0 = $selB1 = $selB2 = $selB3 = "";
// Check if form was submitted
if(isset($_POST['txtSelectBox1'])) {
// Get post values
$txtSel1 = $_POST['txtSelectBox1'];
$txtSel2 = $_POST['txtSelectBox2'];
$txtAmount = $_POST['txtAmount'];
// Exchange rates
$cur = array("MXN", "USD", "EUR", "JPY");
$php = array("1", "0.050", "0.048", "6.78");
$cad = array("20.12", "1", "0.96", "136.50");
$hkd = array("20.99", "1.04", "1", "142.51");
$jpy = array("0.15", "0.0073", "0.0070", "1");
// Switch statement for conversion
switch ($txtSel1) {
case "php":
$selA0 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($php[$txtSel2]);
$case = 0;
break;
case "cad":
$selA1 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($cad[$txtSel2]);
$case = 1;
break;
case "hkd":
$selA2 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($hkd[$txtSel2]);
$case = 2;
break;
case "jpy":
$selA3 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($jpy[$txtSel2]);
$case = 3;
break;
}
// Display output
$out = '<div class="answer">'.$txtAmount.' '.$cur[$case].' = '.$ans.' '.$cur[$txtSel2].'</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Conversor de Divisas</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<div class="container">
<div class="title">
<h1>CONVERSOR</h1>
</div>
<div class="container-wrapper">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="frmSelect" name="frm">
<div class="selectWrapper">
<select class="txtSelectBox" name="txtSelectBox1" id="txtSelectBox1">
<option value="php" <?php echo $selA0; ?>>Peso Mexicano (MXN)</option>
<option value="cad" <?php echo $selA1; ?>>Dolar (USD)</option>
<option value="hkd" <?php echo $selA2; ?>>Euro (EUR)</option>
<option value="jpy" <?php echo $selA3; ?>>Yen Japones (JPY)</option>
</select>
<select class="txtSelectBox" name="txtSelectBox2" id="txtSelectBox2">
<option value="0" <?php echo $selB0; ?>>Peso Mexicano (MXN)</option>
<option value="1" <?php echo $selB1; ?>>Dolar (USD)</option>
<option value="2" <?php echo $selB2; ?>>Euro (EUR)</option>
<option value="3" <?php echo $selB3; ?>>Yen Japones (JPY)</option>
</select>
</div>
<input type="number" class="txtbox" name="txtAmount" id="txtAmount" value="<?php echo $txtAmount; ?>" placeholder="Input Amount" required>
<div class="btnWrapper">
Restaurar
<button type="submit" class="btn btnConvert" name="btnConvert">Convertir</button>
</div>
<?php echo $out; ?>
</form>
</div>
</div>
</main>
</body>
</html>```

Store post form values in hidden input array

I'm new to php and here's my code for a number guessing game. Since I don't know how to define a random number, I chose the number myself, 80. I'm trying to store all the guesses prior to the right one, and after the right guess, print them out on the screen. But I can't seem to be able to get it right since it only prints only the last guess before the right one.
Any help is appreciated!
<html>
<head>
</head>
<body>
<?php
$allguesses = array();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_POST["tmn"] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
array_push($allguesses,$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
foreach($allguesses as $x){
echo "<input type ='hidden' name = 'tmn[]' value=' ".$x . " '>";
}
?>
</form>
</body>
</html>
Sessions seem the best for where you are in your learning curve.
The session allows the normal stateless http protocol to remember things between each submission of a form or forms. So we will save each guess in an array of guesses in the SESSION, which in PHP is an array as well.
<?php
session_start(); // create a session, or reconnect to an existing one
if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["guess"]) ) {
$_SESSION['guesses'][] = $_POST["guess"]; // keep an array of guesses
// $t = $_POST["guess"]; no need for extra variables on the stack
$sayi = 80;
if($sayi > $_POST["guess"]){
echo 'Guess higher';
}elseif($sayi == $_POST["guess"]){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_SESSION['guesses'] as $guess){
echo $guess . ',';
}
$_SESSION['guesses'] = array(); // clear the old guesses out
}else{
echo 'Guess lower';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Removed uneeded codes.
Changed method of showing previous guesses with the below code.
echo implode( ", ", $_POST["tmn"] ); // cleaner
This block handles storing previous guesses into an array that is used for displaying previous guesses.
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
Fixed previous version of below block of code so that hidden <inputs> of previous guesses are outputted properly..
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
Updated Code:
<html>
<head>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
echo implode( ", ", $_POST["tmn"] );
}else{
echo 'Guess lower';
}
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
</form>
</body>
</html>
For random numbers you can use rand($min, $max). to store the guesses you can use the global variable $_SESSION.
<html>
<head>
</head>
<body>
<?php
//start session (needed to use the $_SESSION variable)
start_session();
if($_SERVER["REQUEST_METHOD"] == "POST"){
//if empty -> initalize array
if (empty ($_SESSION['allguesses']){
$_SESSION['allguesses'] = array ()
}
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
//echo all guesses from $_SESSION variable
foreach($_SESSION['allguesses'] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
//push in $_SESSION variable
array_push($_SESSION['allguesses'],$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

if elseif php simple calculator

This is form for calculator
<form method='post' action='result.php' name='calc_form'>
<input type='text' name='input1' size='15'>
<select name='operation'>
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multi">*</option>
<option value="invalid">**</option>
<option value="divide">/</option>
</select>
<input type='text' name='input2' size='15'>
<input type='submit' value='go'>
</form>
This is php with if elseif statement
<?php
define ('INVALID_INPUT', 'ERROR: invalid input');
define ('INVALID_OPERATOR', 'ERROR: invalid operator');
$result = null;
if
(isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
{
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$operation = $_POST['operation'];
switch ($operation)
{
case 'plus':
$result = $input1 + $input2;
break;
case 'minus':
$result = $input1 - $input2;
break;
case 'multi':
$result = $input1 * $input2;
break;
case 'divide':
$result = $input1 / $input2;
break;
default:
$result = INVALID_OPERATOR;
break;
}
}
elseif
(!isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
{
$result = INVALID_INPUT;
}
if ($result !== null)
{
echo <<<EOM
<h2>you calculate</h2> $input1
<h2>and</h2> $input2
<h2>result is:</h2>
$result
EOM;
}
?>
I even tried with only else statement and without condition but it wont show INVALID INPUT when nothing is added in form. What is wrong here?
The problem is with this piece of code:
if
(isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
Even if a user enters nothing in the input fields, they will still pass isset($_POST['input1']), since they are 'set' to an empty string. Try switching it to this instead:
if
(isset($_POST['input1']) && strlen($_POST['input1']) &&
isset($_POST['input2']) && strlen($_POST['input2']) &&
isset($_POST['operation']))
You could just use an else statement instead of an else if statement. That way if you change the inputs you don't have to list each of them twice.
eg:
if (isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
{
// result = calculation
} else
{
// result == code
}
Try this - I tested this on my server and it works!
calculator.php
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',1);;
define ('INVALID_INPUT', 'ERROR: invalid input');
define ('INVALID_OPERATOR', 'ERROR: invalid operator');
$input1 = $input2 = $operation = null;
if (isset($_POST['input1']) and isset($_POST['input2']) and isset($_POST['operation']))
{
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$operation = $_POST['operation'];
if(is_numeric($input1) and is_numeric($input2))
{
switch ($operation)
{
case 'plus':
$result = $input1 + $input2;
break;
case 'minus':
$result = $input1 - $input2;
break;
case 'multi':
$result = $input1 * $input2;
break;
case 'divide':
$result = $input1 / $input2;
break;
default:
$result = INVALID_OPERATOR;
break;
}
}
else
{
$input1 = '';
$input2 = '';
$operation = 'invalid';
$result = INVALID_INPUT;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="">
<form method='POST' action='calculator.php'>
<input type='text' name='input1' size='15' value="<?php echo $input1; ?>">
<select name='operation'>
<option <?php if($operation == 'plus') { echo 'selected';} ?> value="plus">+</option>
<option <?php if($operation == 'minus') { echo 'selected';} ?> value="minus">-</option>
<option <?php if($operation == 'multi') { echo 'selected';} ?> value="multi">*</option>
<option <?php if($operation == 'invalid') { echo 'selected';} ?> value="invalid">**</option>
<option <?php if($operation == 'divide') { echo 'selected';} ?> value="divide">/</option>
</select>
<input type='text' name='input2' size='15' value="<?php echo $input2; ?>">
<span>=</span>
<input type='text' name='result' size='50' value="<?php echo $result; ?>">
<input type='submit' value='go'>
</body>
</html>
Your condition is wrong; this is impossible:
!isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation'])
I suspect you mean
!isset($_POST) or
!isset($_POST['input1']) or
!isset($_POST['input2']) or
!isset($_POST['operation'])

PHP sticky forms dropdown and checkboxes

I'm writing a php form and I can't get the drop down boxes and check boxes to stick as in when I fill in my details but don't click something it will keep everything else filled but that one part that wasn't filled out. I can do it for the input text and radio buttons but I can't get it done for drop downs and checkboxes
<!DOCTYPE html>
<style>
#import url(stickyTextInput.css);
</style>
<?php
if(isset($_REQUEST["left"]))
{
process_form();
}
else
{
display_form_page('');
}
?>
<?php
function display_form_page($error)
{
$self =$_SERVER['PHP_SELF'];
$first_name = isset($_REQUEST['name']) ? $_REQUEST['name']:'';
$last_name = isset($_REQUEST['lastname']) ? $_REQUEST['lastname']:'';
$age = isset($_REQUEST['age']) ? $_REQUEST['age']:'';
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']: '';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head>
<title>
Forms Sticky input
</title>
<style>
#import url(stickyTextInput.css);
</style>
<style type="text/css">
.error
{
color:#ff0000
}
</style>
</head>
<body>
<?php
if($error)
{
echo "<p>$error</p>\n";
}
?>
<form action= "<?php echo $self?>" method = "post">
<h1>Forms-Sticky Input</h1>
<label>First Name:</label>
<input type="text" size="10" maxlength="40" name="name" value = "<?php echo $first_name?>">
<br>
<label>Last Name:</label>
<input type="text" size="10" maxlength="40" name="lastname" value = "<?php echo $last_name?>">
<br>
<label>Age:</label>
<input type="text" name="age" size="10" value="<?php echo $age?>">
<br>
<label>Gender</label>
<input type="radio" name="gender" value="male" <?php check($gender, "male")?>>Male
<input type="radio" name="gender" value="female" <?php check ($gender, "female")?>>Female
<br>
<label>Select favourite Colour</label>
<select name= "color">
<option <?php checkradio($color, "Red")?>>Red
<option <?php checkradio($color, "Blue")?>>Blue
<option <?php checkradio($color, "Green")?>>Green
<option <?php checkradio($color, "Pink")?>>Pink
<option selected="selected" disabled="disabled">
</select>
<br>
<label>Food</label>
<input type="checkbox" name="food[]" value="beans" <?php checkbox ($food, "beans")?>>Beans
<input type="checkbox" name="food[]" value="crisps" <?php checkbox ($food, "crisps")?>>Crisps
<input type="checkbox" name="food[]" value="lemons" <?php checkbox ($food, "lemons")?>>Lemons
<br>
<div id="buttons">
<input type="submit" name="left" id="left" value="Submit" >
<input type="reset" name="right" id="right" value="Reset" >
</div>
</form>
</body>
</html>
<?php
}
?>
<?php
// If $group has the value $val then select this list item
function check($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function checkradio($group, $val)
{
if ($group === $val)
{
echo 'selected = "selected"';
}
}
?>
<?php
// If $group has the value $val then select this list item
function checkbox($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function process_form()
{
$error = validate_form();
if($error)
{
display_form_page($error);
}
else
{
display_output_page();
}
}
?>
<?php
function validate_form()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
$error = '';
$reg_exp = '/^[a-zA-Z\-\']+$/';
$reg_exp1 = '[0-9]{3}';
if(!preg_match($reg_exp, $first_name))
{
$error .= "<span class=\"error\">First Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!preg_match($reg_exp, $last_name))
{
$error .= "<span class=\"error\">Last Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!is_numeric($age))
{
$error .= "<span class=\"error\">Age is invalid (numbers only)</span><br>";
}
if (strlen($gender) == 0)
{
$error .= "<span class=\"error\">Select Male/Female</span><br>";
}
if (strlen($color) == 0)
{
$error .= "<span class=\"error\">Select one color</span><br>";
}
if (! is_array($food))
{
$error .= "<span class=\"error\">You must select one food</span><br>";
}
return $error;
}
?>
<?php
function display_output_page()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head><title>Form Results</title></head>
<body>
<h1>Form Results</h1>
<?php
echo " First Name: $first_name<br/>\n";
echo " Last Name: $last_name<br/>\n";
echo " Age: $age<br/>\n";
echo " Gender: $gender<br/>\n";
echo " Favourite Color: $color<br/>\n";
echo "<ul>";
if (is_array($food))
{
echo "Favourite Food is:";
foreach($food as $selection)
{
echo "<li>$selection</li>";
}
}
echo "</ul>";
?>
</body>
</html>
<?php
}
?>
Possibly a browser issue, however most browsers only require 'checked' at the end of the html input element for checkboxes. However you appear to be outputting checked = "checked" This is possibly the problem. Have a look at the sample below:
<?php
$name = isset($_GET['name']) ? $_GET['name'] : '';
$agree = isset($_GET['agree']) ? 'checked' : '';
$title = isset($_GET['title']) ? $_GET['title'] : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="name" id="name" value="<?=$name;?>">
<input type="checkbox" name="agree" id="agree" <?=$agree;?>>
<select name="title" id="title">
<option value="Mr" <?=$title == 'Mr' ? 'selected' : ''?>>Mr</option>
<option value="Mrs" <?=$title == 'Mrs' ? 'selected' : ''?>>Mrs</option>
<option value="Miss" <?=$title == 'Miss' ? 'selected' : ''?>>Miss</option>
</select>
<button type="submit">submit</button>
</form>
</body>
</html>
After processing the values the output html should be as follows:
<form action="">
<input type="text" name="name" id="name" value="test">
<input type="checkbox" name="agree" id="agree" checked>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss" selected>Miss</option>
</select>
<button type="submit">submit</button>
</form>

Simple PHP calculator

I'm creating a basic PHP calculator that lets you enter two values and chose your operator then displays the answer. Everything is working fine except it's not outputting the answer to the browser.
Here are the codes for my html and PHP files:
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form method="post" attribute="post" action="disp_form.php">
<p>First Value:<br/>
<input type="text" id="first" name="first"></p>
<p>Second Value:<br/>
<input type="text" id="second" name="second"></p>
<input type="radio" name="group1" id="add" value="add" checked="true"><p>+</p><br/>
<input type="radio" name="group1" id="subtract" value="subtract"><p>-</p><br/>
<input type="radio" name="group1" id="times" value="times"><p>x</p><br/>
<input type="radio" name="group1" id="divide" value="divide"><p>/</p><br/>
<p></p>
<button type="submit" name="answer" id="answer" value="answer">Calculate</button>
</form>
</body>
</html>
PHP file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<p>The answer is:
<?php
if($_POST['group1'] == add) {
echo "$first + $second";
}
else if($_POST['group1'] == subtract) {
echo "$first - $second";
}
else if($_POST['group1'] == times) {
echo "$first * $second";
}
else($_POST['group1'] == divide) {
echo "$first / $second";
}
?>
</p>
</body>
</html>
<?php
$result = "";
class calculator
{
var $a;
var $b;
function checkopration($oprator)
{
switch($oprator)
{
case '+':
return $this->a + $this->b;
break;
case '-':
return $this->a - $this->b;
break;
case '*':
return $this->a * $this->b;
break;
case '/':
return $this->a / $this->b;
break;
default:
return "Sorry No command found";
}
}
function getresult($a, $b, $c)
{
$this->a = $a;
$this->b = $b;
return $this->checkopration($c);
}
}
$cal = new calculator();
if(isset($_POST['submit']))
{
$result = $cal->getresult($_POST['n1'],$_POST['n2'],$_POST['op']);
}
?>
<form method="post">
<table align="center">
<tr>
<td><strong><?php echo $result; ?><strong></td>
</tr>
<tr>
<td>Enter 1st Number</td>
<td><input type="text" name="n1"></td>
</tr>
<tr>
<td>Enter 2nd Number</td>
<td><input type="text" name="n2"></td>
</tr>
<tr>
<td>Select Oprator</td>
<td><select name="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value=" = "></td>
</tr>
</table>
</form>
Personally I would do a switch instead of all this if, else if, else
$first = $_POST['first'] + 0;//a small "hack" to make sure its an int but allow negs!!
$second= $_POST['second'] + 0;
$operator = $_POST["group1"];
switch($operator)
{
case "add"
echo "Answer is: " .$first + $second;
break;
case "subtract"
echo "Answer is: " .$first - $second;
break;
case "times"
echo "Answer is: " .$first * $second;
break;
case "divide"
echo "Answer is: " .$first / $second;
break;
}
You need to assign $first and $second
$first = $_POST['first'];
$second= $_POST['second'];
Also, As Travesty3 said, you need to do your arithmetic outside of the quotes:
echo $first + $second;
You also need to put the [== 'add'] math operation into quotes
if($_POST['group1'] == 'add') {
echo $first + $second;
}
complete code schould look like that :
<?php
$first = $_POST['first'];
$second= $_POST['second'];
if($_POST['group1'] == 'add') {
echo $first + $second;
}
else if($_POST['group1'] == 'subtract') {
echo $first - $second;
}
else if($_POST['group1'] == 'times') {
echo $first * $second;
}
else if($_POST['group1'] == 'divide') {
echo $first / $second;
}
?>
You need to get the values the same way to get the calculator operation which looks like:
<?php
if($_POST['group1'] == add) {
echo "$_POST['first']+ $_POST['second'];
}
... and so on
?>
Or, to make it easier, just do:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<p>The answer is:
<?php
$first = $_POST['first'];
$second= $_POST['second'];
if($_POST['group1'] == add) {
echo "$first + $second";
}
else if($_POST['group1'] == subtract) {
echo "$first - $second";
}
else if($_POST['group1'] == times) {
echo "$first * $second";
}
else($_POST['group1'] == divide) {
echo "$first / $second";
}
?>
</p>
</body>
</html>
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
Check string using single quotes
Ex. $_POST['group1'] == 'add'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculator</title>
</head>
<body>
HTML Code is here:
<form method="post">
<input type="text" name="numb1">
<input type="text" name="numb2">
<select name="operator" id="">
<option>None</option>
<option>Add</option>
<option>Subtract</option>
<option>Multiply</option>
<option>Divide</option>
<option>Square</option>
</select>
<button type="submit" name="submit" value="submit">Calculate</button>
</form>
PHP Code:
<?php
if (isset($_POST['submit'])) {
$result1 = $_POST['numb1'];
$result2 = $_POST['numb2'];
$operator = $_POST['operator'];
switch ($operator) {
case 'None':
echo "You need to select any operator";
break;
case 'Add':
echo $result1 + $result2;
break;
case 'Subtract':
echo $result1 - $result2;
break;
case 'Multiply':
echo $result1 * $result2;
break;
case 'Divide':
echo $result1 / $result2;
break;
case 'Square':
echo $result1 ** $result2;
break;
}
}
?>
enter code here
</body>
</html>
Make this changes in php file
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<p>The answer is:
<?php
$first = $_POST['first'];
$second= $_POST['second'];
if($_POST['group1'] == 'add') {
echo $first + $second;
}
else if($_POST['group1'] == 'subtract') {
echo $first - $second;
}
else if($_POST['group1'] == 'times') {
echo $first * $second;
}
else if($_POST['group1'] == 'divide') {
echo $first / $second;
}
else {
echo "Enter the numbers properly";
}
?>
</p>
</body>
</html>
<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];
if($symbol == '+')
{
$add = $cal1 + $cal2;
echo "Addition is:".$add;
}
else if($symbol == '-')
{
$subs = $cal1 - $cal2;
echo "Substraction is:".$subs;
}
else if($symbol == '*')
{
$mul = $cal1 * $cal2;
echo "Multiply is:".$mul;
}
else if($symbol == '/')
{
$div = $cal1 / $cal2;
echo "Division is:".$div;
}
else
{
echo "Oops ,something wrong in your code son";
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form method="GET">
<h1>Calculator</h1>
<p>This is a calculator made by Hau Teen Yee Fabrice and is free to use.</p>
<ul>
<ol> Multiplication: * </ol>
<ol> Substraction: - </ol>
<ol> Division: / </ol>
<ol> Addition: + </ol>
</ul>
<p>Enter first number:</p>
<input type="text" name="cal1">
<p>Enter second number:</p>
<input type="text" name="cal2">
<p>Enter the calculator symbol</p>
<input type="text" name="symbol">
<button>Calculate</button>
</form>
<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];
if($symbol == '+')
{
$add = $cal1 + $cal2;
echo "Addition is:".$add;
}
else if($symbol == '-')
{
$subs = $cal1 - $cal2;
echo "Substraction is:".$subs;
}
else if($symbol == '*')
{
$mul = $cal1 * $cal2;
echo "Multiply is:".$mul;
}
else if($symbol == '/')
{
$div = $cal1 / $cal2;
echo "Division is:".$div;
}
else
{
echo "Oops ,something wrong in your code son";
}
?>
</body>
</html>

Categories