Nicholas
Nicholas

Reputation: 29

Echoing out results from dropdownlist

I need some help with my code.

What I need to do is have a dropdownlist with values and once you select the value it will minus another delcared value and finally echo out the new value. This is what I've tried so far however there are errors which I couldn't solve.

<html>
<form action="" method="post">
<select name="list" id="list">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</html>
<?php
$options = array(
    '1' => 1,
    '2' => 2,
);

$value = $_POST['list'];
$cmeter = 100;

$newcmeter = $cmeter - $options[$value] ;
 echo $newcmeter;
?>

Errors are:

[03-Jan-2012 02:02:03] PHP Notice:  Undefined index: list in C:\www\abc\hello.php on line 16

[03-Jan-2012 02:02:03] PHP Notice:  Undefined index:  in C:\www\abc\hello.php on line 19

Upvotes: 2

Views: 398

Answers (1)

Marc B
Marc B

Reputation: 360672

You code runs unconditionally, whether that form has been submitted or not. When the form hasn't been submitted, there's no $_POST['list'] value, hence the errors. Since you're using POSt, the fix is simple:

... form stuff here...

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   ... your php processing stuff here ...
}

That'll make the code run ONLY when a POST has actually been performed. However, for maximum safety, you should also validate the submitted data:

if (isset($_POST['list'])) {
    $value = (int)$_POST['list'];
} else {
    $value = 0; // default value;
}

Upvotes: 2

Related Questions