1

我收到错误说 $id1 和 $id2 未定义。我没有正确访问它们吗?如果不是,我该如何正确访问它们?

$query = $this->db->query("SELECT * FROM churchMembers");
$row = $query->row();
    if ($query->num_rows() != 0) {
      if ($postingUserId == $row->cMuserId) { // check to see what church the posting user is a member of
        $id1 = $row->cMchurchId; // if posting user is a member of a church set it to var id1
      } 
      if ($userid == $row->cMuserId) { // check to see what church myuserid is a member of
        $id2 = $row->cMchurchId; // if myuserid is a member of a church set it to var2
      } 
      if ($id1 == $id2) { // if posting user and myuserid are a member of the same church process the following
        echo json_encode(array('loggedIn' => true, 'isMembershipSame' => true));
      } 
      elseif ($id1 != $id2) { // if posting user and myuserid are not a member of the same user process the following
        echo json_encode(array('loggedIn' => true, 'isMembershipSame' => false));
      }
    }
4

1 回答 1

3

除非满足它们的相应条件,否则您不定义任何一个$id1或不定义,因此如果上述任一条件为 false 并且不运行,则当您尝试在.$id2ifif ($id1 == $id2)

您应该在输入 if 链之前将它们初始化为空字符串。然后在比较它们时,还要验证它们是否为非空:

// ADDENDUM after comments:
// If you put this into a loop to fetch rows,
// the following must be INSIDE the loop to reinitialize
// the two vars on each iteration.

// Initialize them as empty strings
$id1 = "";
$id2 = "";

// If you are in a loop, you should check num_rows() once outside the loop, rather than inside
if ($query->num_rows() != 0) {
  if ($postingUserId == $row->cMuserId) {
    $id1 = $row->cMchurchId;
  } 
  if ($userid == $row->cMuserId) {
    $id2 = $row->cMchurchId;
  } 
  // Test if they are non-empty (conditions matched above) and equal:
  if (!empty($id1) && !empty($id2) && $id1 == $id2) {
    echo json_encode(array('loggedIn' => true, 'isMembershipSame' => true));
  } 
  // No need for else if here, just a plain else clause
  else {
    echo json_encode(array('loggedIn' => true, 'isMembershipSame' => false));
  }
}
于 2012-08-19T02:56:15.697 回答