MySQL返回相反的值

时间:2013-12-31 19:57:28

标签: php mysql pdo forum

非常感谢大家,原来我只是将错误的数据放入数据库。

我有一两个问题。我目前正在开发一个php论坛,我需要得到他们的topc_cat等于1的所有记录。问题是,它返回相反的(它只返回值,如果它不等于1)。我不确定为什么会这样。这是我的代码:

public function getFrom($table, $where){
    $sql = "SELECT * FROM {table} WHERE 'topic_cat' = {$where}"; 
    if ($this->_query = $this->_pdo->prepare($sql)) {           
        if ($this->_query->execute()) {
            $this->results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        }
    }
    return $this->results;
}

$where的值为1时,它不返回任何内容。如果我将其更改为WHERE 'topic_cat' != {$where},则会返回:

stdClass Object ( [topic_id] => 1 [topic_subject] => Test Topic [topic_date] => 2013-12-31 19:42:01 [topic_cat] => 1 [topic_by] => 0 ) stdClass Object ( [topic_id] => 2 [topic_subject] => Test Topic 2 [topic_date] => 2013-12-31 19:42:01 [topic_cat] => 1 [topic_by] => 0 )

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

不要在列名中使用quation而你也错过了表变量中的$:试试这个:

public function getFrom($table, $where){
    $sql = "SELECT * FROM $table WHERE topic_cat = {$where}"; 
    if ($this->_query = $this->_pdo->prepare($sql)) {           
        if ($this->_query->execute()) {
            $this->results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        }
    }
    return $this->results;
}

答案 1 :(得分:0)

在这种情况下,您的问题是您正在使用字符串文字'topic_cat',这意味着您正在评估字符串'topic_cat'(而不是列topic_cat)等于$ where的情况。你还确定{table}不应该是{$ table}吗?

从风格上来说,既然你正在使用预准备语句,为什么不在准备时使用命名属性并注入它们呢? e.g。

$sql = "SELECT * FROM table WHERE topic_cat = :topicCatWhere";
if ($this->_query = $this->_pdo->prepare($sql, array(':topicCatWhere' => $where))) { 
   ...
}