'如果'语句条件代码未按预期运行

时间:2016-03-19 22:00:18

标签: php

我真的不明白这段代码是如何弄乱的,但它只是,我从来没有遇到任何类似的事情,所以如果有人能解释发生了什么,我会非常高兴。< / p>

代码:$functions->update("batzz",$functions->getPlayerInfo("batzz"));无论if条件是否满足都会运行,这开始变得非常令人沮丧。

这是代码的完整摘录。它周围没有循环,当它运行时,它会输出正确的语句,但无论if是true还是false,它都会运行更新函数。

if($functions->checkRecordsExist($_GET['name']) == false) {
    $functions->update("batzz",$functions->getPlayerInfo("batzz"));
    echo "Your account has been updated! Visit your page <a href='/osrstracker/name/". $_GET['name'] ."'>here</a>";
} else {
    echo "Oops, either you havess already updated your account within the past 12 hours or we have messed something up!";
}

我很想知道这可能会发生什么,如果我能解决它,因为它非常烦人!

功能代码:$functions->checkRecordsExist($_GET['name']) == false

public function checkRecordsExist($dpname){
        $curdate = date("Y-m-d H:i:s");
        $olddate = date('Y-m-d H:i:s', strtotime('-12 hour'));
        $this->query("SELECT * FROM stats JOIN accounts ON stats.userid = accounts.id  WHERE accounts.displayName=:dpname AND stats.date BETWEEN '$olddate' AND '$curdate';");
        $this->bind(":dpname",$dpname);
        $result = $this->resultSet();

        if(!empty($result)){
            if($result[0]['rank'] == 1){
                $this->query("SELECT * FROM stats JOIN accounts ON stats.userid = accounts.id  WHERE accounts.displayName=:dpname AND stats.date BETWEEN '$olddate' AND '$curdate';");
                $this->bind(":dpname",$dpname);
                $result2 = $this->resultSet();
                if(empty($result2)){
                    return false;
                }

            }
            return true;
        }
        return false;
    }

准备查询后的PDO对象

object(PDOStatement)#3 (1) {
  ["queryString"]=>
  string(171) "SELECT * FROM stats JOIN accounts ON stats.userid = accounts.id  WHERE accounts.displayName=:dpname AND stats.date BETWEEN '2016-03-19 11:48:36' AND '2016-03-19 23:48:36';"
}

2 个答案:

答案 0 :(得分:0)

因为你正在使用==而不是===我会打赌你实际上从这个函数得到一个null,空字符串或0 - 这等同于false但不是布尔值。如果您使用“=== false”比较或反向顺序并执行“!== false”“或=== true”比较,那将强制检查类型为布尔值并可能解决您的问题。

答案 1 :(得分:0)

可能不是一个答案,但对评论来说太过分了。我相信问题在这里:

$result = $this->resultSet();

if(!empty($result)){
    if($result[0]['rank'] == 1){

我认为$result[0]['rank']永远不会1,因此您在第二个return true声明后点击了if

我建议检查结果,甚至可能重写这样的逻辑:

// no result means false.
if (empty($result)){
    return false;
}

// if the result is NOT a match return true (is this correct?)
if ($result[0]['rank'] != 1){
    return true;
}

// must be a matched result, check for a second result
$this->query("SELECT * FROM stats JOIN accounts 
    ON stats.userid = accounts.id
    WHERE accounts.displayName=:dpname AND stats.date 
    BETWEEN '$olddate' AND '$curdate';");
$this->bind(":dpname",$dpname);
$result2 = $this->resultSet();

// invert result of empty() as final return value (is this correct?)
return (! empty($result2));