尝试从数据库中查看表,但显然我的语法不正确,尽管它与PHPmyAdmin上的查询匹配

时间:2012-11-11 23:44:58

标签: php mysql

澄清我的数据库被称为数据库,我的表被称为表(这是用于测试)。

  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 table

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便在表格附近使用&#39; table&#39;在第2行

感谢。

1 个答案:

答案 0 :(得分:2)

table是MySQL中的reserved word,因此您必须将其转义。你可以把`放在它周围。

例如:

SELECT * FROM `table`

正如你在我的链接上看到的那样,有几个棘手的保留字会引起很多麻烦。有人说在编写表和字段名时应始终使用`个字符。