CodeIgniter没有正确访问if ... else语句中的变量

时间:2012-08-19 02:47:08

标签: php mysql codeigniter

我收到错误,说$ 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));
      }
    }

1 个答案:

答案 0 :(得分:3)

除非满足相应的$id1条件,否则不会定义$id2if,因此,如果上述任一条件为false且未运行,则两个变量都不存在当您尝试在if ($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));
  }
}
相关问题