2014-02-06 62 views
0

我已經DB命名CMS有兩列:iddata1PDO sql語法錯誤?

我獲得以下錯誤試圖從數據庫中讀取數據時,下面的代碼。

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table' at line 1' in /var/pdo/index.php:4 Stack trace: #0 /var/pdo/index.php(4): PDO->query('SELECT * FROM t...') #1 {main} thrown in /var/pdo/index.php on line 4

爲什麼我會收到此錯誤?

這是我的代碼:

<?php 
    $db = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'root', 'password'); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 

    $stmt = $db->query('SELECT * FROM table'); 

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     echo $row['field1']; 
    } 
?> 
+0

不要使用表作爲表名.. – randomizer

+0

您的數據庫被稱爲CMS。什麼叫表? –

回答

7

table是一個保留字。完整列表請參見http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html

你可以使用反引號(SELECT * FROM `table`)如果你仍然想使用你的表名「表」

+0

確實是:[保留字](http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html) – Melon

+0

擊敗了我5秒。 – bart2puck

+1

@ bart2puck你的回答比較好,但是因爲'\'table \''會起作用。 – kelunik