I’m going through a very basic php tutorial and am creating a calculator so I can get the hang of $_GET, $_POST and some general syntax.
I created a very basic php function calc(); in a php file called functionadvanced.php. All it does is take 2 numbers, an operator, does the math and spits out the results (like I said, very basic tutorial). The function works so I won’t post the code.
I have another php file called calc.php that has my form for my calculator. Here’s the code:
<?php
include "functionadvanced.php";
$number1 = $_POST['num1'];
$number2 = $_POST['num2'];
$operator = $_POST['op'];
?>
<html>
<body>
<form action='calc.php' method='POST'>
<input type='textbox' name='num1' value="<?php echo $_GET['$number1']; ?>"/>
<select name="op" selected="<?php echo $_GET['$operator']; ?>">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type='textbox' name='num2' value="<?php echo $_GET['$number2']; ?>"/>
<input type='submit' value='=' />
<input type='text' name='result' value="<?php echo calc($number1,$number2,$operator); ?>" />
</form>
</body>
</html>
The form actually works, and shows the correct value that the calc function spits out, but when the page posts back it doesn’t keep the posted back values in the fields. I thought I was suppose to use a $_GET to grab the values posted in the $_POST?
$_GETrefers to information passed in the query string (index.php?id=123gives$_GET['id'] = '123'), while$_POSTis for form info. These correspond roughly (but not exactly) to the matching http request methods.So you want to use
$_POSTagain, or just use the variables you’ve already read from$_POST(like$number1).NOTE: I know this is just a learning process, but this naive approach is vulnerable to XSS, so read up on that before going live with anything important…