简体   繁体   English

如果声明(PDO :: FETCH_ASSOC)有问题

[英]If statement (PDO::FETCH_ASSOC) trouble

Running into trouble with the function below. 使用下面的功能遇到麻烦。 Basically all my tables have a column in which 'discontinued' will either be '0' or '1'. 基本上我的所有表都有一个列,其中'不连续'将为'0'或'1'。 I'm having trouble getting the if statement to work. 我无法使if语句生效。

// Function that checks if items are already discontinued or not
function checkDiscontinued($dbh, $discontinued) {
try {
    foreach ($discontinued as $id) {
        //check to see if itemdiscontinued is 1 or 0
        $stmt = $dbh->query("SELECT discontinued FROM `$id` ORDER BY `date` DESC LIMIT 1");

        if (!$stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "Action if true";
        }   else {
        echo "Action if false";
        }
    }
}
    catch (PDOException $e) {
    echo $e->getMessage();
    }
}

The fetch() method will always return true, no matter what your columns return as a result set (it should be common sense I guess). 无论你的列作为结果集返回什么,fetch()方法总是返回true(我猜这应该是常识)。

What you need is to assign the value of the column to variable, and test the value. 您需要的是将列的值分配给变量,并测试该值。

const DISCONTINUED = 1;

function checkDiscontinued($dbh, $discontinued) {
try {
    foreach ($discontinued as $id) {
        $stmt = $dbh->query("SELECT discontinued FROM `$id` ORDER BY `date` DESC LIMIT 1");

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($row['discontinued'] == self::DISCONTINUED) { //if the column result == '1'
            echo "Action if true";
        }   else {
            echo "Action if false";
        }
    }
}
    catch (PDOException $e) {
        echo $e->getMessage();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM