Page 1 of 1

undefined index ??

Posted: Wed Feb 27, 2008 3:58 pm
by dannyd
**** PLEASE USE THE CODE TAG *****

Code: Select all

<?PHP
 
$p1 = $_POST['p1'];
$p2 = $_POST['p2'];
$p3 = $_POST['p3'];
 
 
 
$total = $p1 + $p2 + $p3;
 
echo "Your Total is: " . $total;
 
 
 
?>

How come I get an Undefined Index error with this code ? What am i doing wrong ? How do you get this error ?

Re: undefined index ??

Posted: Wed Feb 27, 2008 4:41 pm
by Christopher
Better would be:

Code: Select all

$p1 = isset($_POST['p1']) ? intval($_POST['p1']) : 0;
$p2 = isset($_POST['p2']) ? intval($_POST['p2']) : 0;
$p3 = isset($_POST['p3']) ? intval($_POST['p3']) : 0;

Re: undefined index ??

Posted: Wed Feb 27, 2008 9:10 pm
by Ambush Commander
Or even better

Code: Select all

 
function postInt($key) {
  if (!isset($_POST[$key])) return 0;
  return intval($_POST[$key]);
}
$p1 = postInt('p1');
$p2 = postInt('p2');
$p3 = postInt('p3');