2012-11-11 13 views
3

來澄清我的數據庫被稱爲數據庫和我的表被稱爲表(這是測試)。試圖從數據庫查看錶,但顯然我有不正確的語法,儘管它匹配PHPmyAdmin上的查詢

class Database 
{ 
public $server = "localhost"; 
public $database = "database"; 
public $user = "root"; 
public $password = ""; 
public $row; 
public $result; 



//call connection method upon constructing 
public function __construct(){ 
    $this->createConnection(); 
} 

//connection to the database 
public function createConnection() 
    { 
    $this->dbLocalhost = mysql_connect($this->server, $this->user, $this->password) 
       or die("could not connect:".mysql_error()); 

     mysql_select_db($this->database) 
     or die("Could not find the database: ".mysql_error()); 
} 

//execute query string 
public function query($queryString) 
    { 

     echo "<table border='1' cellpadding='10'>"; 
     echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>"; 
     $this->result = mysql_query($queryString) 
     or die($queryString."<br/><br/>".mysql_error()); 

     while($this->row = mysql_fetch_array($this->result)) { 

       echo "<tr>"; 
       echo '<td>' . $this->row['id'] . '</td>'; 
       echo '<td>' . $this->row['firstname'] . '</td>'; 
       echo '<td>' . $this->row['lastname'] . '</td>'; 
       echo '<td><a href="edit.php?id=' . $this->row['id'] . '">Edit</a></td>'; 
       echo '<td><a href="delete.php?id=' . $this->row['id'] . '">Delete</a></td>'; 
       echo "</tr>"; 

     } 

     echo "</table>"; 
    } 

然後我有調用函數的php文件。

<?php 

include('database.php'); 
$db = new Database(); 
$sql = "SELECT * 
    FROM table"; 
$db->query($sql); 

?> 

這是錯誤接收:

SELECT * FROM表

您的SQL語法錯誤;檢查對應於您的MySQL服務器版本的手冊,以便在第2行'table'附近使用正確的語法。

謝謝。

+0

是你的桌子嗎?!?! – Andbdrew

+0

是啊,數據庫被稱爲數據庫 – normower

回答

2

table是在MySQL中的reserved word,所以你必須逃避它。你可以通過在周圍放置`來做到這一點。

例如:

SELECT * FROM `table` 

如你我的鏈接上看到,有可能會導致很多頭痛的幾個棘手的保留字。有人說,在編寫表格和字段名稱時,應始終使用`個字符。

+0

然後我剛剛收到: SELECT * FROM'table' 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第2行的''table''附近使用正確的語法。 – normower

+1

@ user1816869不,它是一個不同的字符。我的意思是',而不是'。它被稱爲反引號。 en-us鍵盤左上角。 – kapa

+0

哇我覺得很蠢,我用一個新名字創建了一個新表。感謝您的幫助 – normower

相關問題