2

Have I missed something here that I'm not seeing that would throw an undefined index error for this code? In testing a addition of code to functions.php where $_POST['sub'] is not being passed it throws the undefined index error below, but this same isset() test against the exact same POST variable "sub" is performed about 12 times above line 494 without throwing error. What am i missing?

ERROR FROM PHP

Notice: Undefined index: sub in /home/path/public_html/dtest/includes/functions.php on line 494

CODE FOR LINE 494

if (isset($_POST['sub']) && $_POST['sub'] == "ritem") {
    $id = $_POST['ritemid'];
    unset($_SESSION['cart']['items'][$id]);
    header("Location: ".$_SERVER['HTTP_REFERER']."");
    die();
} else {
    echo $_POST['sub'];
}
Vickel
  • 7,879
  • 6
  • 35
  • 56
DMSJax
  • 1,709
  • 4
  • 22
  • 35
  • You have to use the isset first, and then check to see if it is "ritem" – Chitowns24 Mar 28 '14 at 19:08
  • @Chitowns24 But his error says undefined index **sub** - me thinks this isn't all the code – Mike B Mar 28 '14 at 19:09
  • Yeah, I just re-looked at it I agree – Chitowns24 Mar 28 '14 at 19:11
  • @MikeB Thats all the code for it, but answer below is correct - now that i look at it from top to bottom the ELSE part of that statement should have been removed some time back. Looks like it got left in there. – DMSJax Mar 28 '14 at 19:16
  • This is why there's line-length limits and standards disallowing one-line control structures. Clean code looks like this http://codepad.org/BTGPtnbE – Mike B Mar 28 '14 at 19:22

2 Answers2

1

Remove the echo $_POST['sub']; from the else part which is responsible for this Undefined index notice and replace with the echo statement.

Should be like this..

<?php

if (isset($_POST['sub']) && $_POST['sub']=="ritem") {
    $id=$_POST['ritemid'];
    unset ($_SESSION['cart']['items'][$id]);
    header("Location: ".$_SERVER['HTTP_REFERER']."");die();}
else
{
 echo "The subject is not set";    
}

That is because.. when the if fails which means the $_POST['sub'] is not set , so when it comes to the else part , you are trying to output $_POST['sub'] which was actually not set (which is actual source of this problem)

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • 1
    Thanks - after looking it back over the ELSE statement should have been removed at an earlier revision and someone overlooked it and left in it. Removing it fixed the issue - sorry it was such a trivial thing, guess I was just as guilty of overlooking it as the other developers – DMSJax Mar 28 '14 at 19:18
0

Its because of else case

if (isset($_POST['sub']) && $_POST['sub']=="ritem") {
  $id=$_POST['ritemid'];
  unset ($_SESSION['cart']['items'][$id]);
  header("Location: ".$_SERVER['HTTP_REFERER']."");
  die();
} else if(isset($_POST['sub'])) {
  echo $_POST['sub'];
} else {
  // Do something else here
}
Rahul Prasad
  • 8,074
  • 8
  • 43
  • 49