为什么我会收到“SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法中有错误......”? (PDO-PHP)

时间:2014-01-10 18:52:25

标签: php mysql syntax-error

我知道这个问题已被多次询问但是从我看过的很多问题来看,似乎他们总是使用mysql保留关键字作为表或列名,或者实际上在这里或那里有语法错误,但我不知道我想我也是如此,我很感激帮助弄清楚为什么我会这样做。这是导致错误的函数:

public function user_exists($db, $username) {
    $query = $db->prepare("SELECT COUNT('id') FROM 'users' WHERE 'username' = ?");
    $query->bindValue(1, $username);

    try {
        $query->execute();
        $rows = $query->fetchColumn();

        if($rows == 1) {
            return false;
        }
        else {
            return true;
        }
    }
    catch(PDOException $e) {
        die($e->getMessage());
    }
}

然后当用'username'参数调用',任何'时,这是我得到的完整错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your  SQLsyntax; check the manual that corresponds to your MySQL server version for the right  syntax to use near ''users' WHERE 'username'= anything' at line 1

2 个答案:

答案 0 :(得分:3)

使用反引号来转义表名或列名,而不是引号。

SELECT COUNT(`id`) FROM `users` WHERE `username` = ?

答案 1 :(得分:2)

使用反引号:

更改

"SELECT COUNT('id') FROM 'users' WHERE 'username' = ?"

"SELECT COUNT(`id`) FROM `users` WHERE `username` = ?"