2014-01-14 61 views
0

遇到以下功能出现问题。基本上我所有的表格都有一列,其中'已停用'将是'0'或'1'。我无法使if语句正常工作。如果声明(PDO :: FETCH_ASSOC)有问题

// 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(); 
    } 
} 
+0

“我无法让if语句工作” - 这是什么意思?如何“停止”存储?它的类型是什么? – Shoe

回答

2

的fetch()方法将总是返回true,不管你是什么列返回的结果集(应该是常识我猜)。

您需要将列的值分配给变量并测试值。

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(); 
    } 
} 
+0

繁荣!感谢那! – DrDog