0

我正在使用标题功能根据某些条件定位到另一个页面。我正在监视一个邮箱,代码根据发件人地址重定向到另一个页面。除了一个之外,所有标题都在工作。如果发件人不属于任何现有组,我想将其重定向到 new.php。但它不是重定向。我无法弄清楚为什么。请帮我。

<?php 
session_start();

$server = '{server}INBOX';
$username = 'aaa@bbb.com';
$password = 'password';
require_once '../swift/lib/swift_required.php';
include('connection.php');


$connection  = imap_open($server,$username,$password) or die('Cannot connect to Gmail: ' .    imap_last_error());

$_SESSION['connection']=$connection;

$result = imap_search($connection,'UNSEEN');
if($result) {

    rsort($result);

    foreach($result as $email_number) 
    {         

        $header = imap_headerinfo($connection, $email_number);

        $fromaddr = $header->from[0]->mailbox . "@" . $header->from[0]->host;

        $query = "select * from usergroup where email='$fromaddr'";
        $_SESSION['fromaddr']=$fromaddr;

        $result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());


        while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
        {
            $email=$line['email'];
            $group=$line['group'];

            if(mysql_num_rows($result1) == 1){

                if($group == 1){
                    header("Location: facilitator.php");
                }
                elseif($group == 2){
                    header("Location: learner.php");
                }

            }
            elseif (mysql_num_rows($result1) == 0) {
                header("Location: new.php");
            }

        }
    }

}
elseif (!$result)
{
     echo "No unread messages found";
}


?>
4

2 回答 2

3

看起来好像您将该重定向嵌套在 while 循环中。由于没有行,while 条件mysql_fetch_array()将立即返回FALSE并跳过整个块,包括您希望它遵循的重定向。

将测试移到循环mysql_num_rows()外。while

// Test for rows and redirect BEFORE entering the while loop.
if (mysql_num_rows($result1) === 0) {
  header("Location: new.php");
  // Always explicitly call exit() after a redirection header!
  exit();
}
// Otherwise, there are rows so loop them.
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
   $email=$line['email'];
   $group=$line['group'];

   if($group == 1){
     header("Location: facilitator.php");
   }
}

实际上,您可能根本不需要while循环,具体取决于您期望获取的行数。如果您只希望每封电子邮件有一组,那么请放弃循环并只调用$line = mysql_fetch_array()一次。但是,如果您期望多行但希望在遇到 where 的第一个行上重定向$group == 1,那么您的逻辑有效。但是,在这种情况下,由于您只执行重定向而没有其他操作,您不妨将该条件放在查询中:

// Test the group in your query in the first place.
$query = "select * from usergroup where email='$fromaddr' AND group = 1";
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());

if (mysql_num_rows($result1) === 0) {
  // you didn't match a row, redirect to new.php
} 
else {
  // you had a match, redirect to facilitator.php
}
于 2012-10-10T18:38:34.223 回答
1

简单的一:

改变:

elseif (mysql_num_rows($result1) == 0){

到:

else {

中的条件else if可能是错误的 - 所以你没有进入那里,因此不会发生重定向。

于 2012-10-10T18:37:14.983 回答