2015-07-13 145 views
-1

我有寫有PDO的SQL查詢,我得到這個錯誤:PDO SQL查詢選擇

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;

我的代碼是:

$dbh = new PDO("mysql:host=$hostname;charset=utf8;dbname=$database", $username, $password); 
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$sql = "SELECT 
      '".$perfix."'_k2_items.id AS `ItemId`, 
      '".$perfix."'_k2_items.title AS `Title`, 
      '".$perfix."'_k2_items.alias AS `Alias`, 
      '".$perfix."'_k2_items.catid AS `CatId`, 
      LEFT('".$perfix."'_k2_items.introtext,1000) AS `Fulltext`, 
      '".$perfix."'_k2_items.created AS `created`, 
      '".$perfix."'_k2_categories.name AS `CatName` 
      FROM '".$perfix."'_k2_items 
      INNER JOIN '".$perfix."'_k2_categories 
      ON '".$perfix."'_k2_items.catid = '".$perfix."'_k2_categories.id 
      WHERE '".$perfix."'_k2_items.featured = '1' "; 

的錯誤是前綴。我認爲我犯了一個sytax錯誤。

你能幫我嗎?

謝謝

+0

'$ perfix'的價值是什麼?你爲什麼用引號(')括起來? – vhu

+0

Pefix是一種刺痛。是sql表的perfix。這是一個:$ perfix =「table1」;引號(')是因爲我在代碼的開始處使用了雙引號。 –

+0

@JamesFourikis我已經更新了我的答案。 – Hassaan

回答

0

我剛剛從'".$perfix."'刪除'

嘗試

$dbh = new PDO("mysql:host=$hostname;charset=utf8;dbname=$database", $username, $password); 
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$sql = "SELECT 
      ".$perfix."_k2_items.id AS `ItemId`, 
      ".$perfix."_k2_items.title AS `Title`, 
      ".$perfix."_k2_items.alias AS `Alias`, 
      ".$perfix."_k2_items.catid AS `CatId`, 
      LEFT(".$perfix."_k2_items.introtext,1000) AS `Fulltext`, 
      ".$perfix."_k2_items.created AS `created`, 
      ".$perfix."_k2_categories.name AS `CatName` 
      FROM ".$perfix."_k2_items 
      INNER JOIN ".$perfix."_k2_categories 
      ON ".$perfix."_k2_items.catid = ".$perfix."_k2_categories.id 
      WHERE ".$perfix."_k2_items.featured = '1' "; 
+0

謝謝。有效! –

+0

@JamesFourikis我很高興它適合你。如果您覺得它有用,請接受我的回答。 – Hassaan

0

單引號是不是屬於添加到查詢每個變量。單引號在SQL中有非常特殊的含義,只有在需要時才能使用。對於部分表名稱他們不是。

另外,學習使用表別名,使你的SQL更少。

$sql = "SELECT i.id, i.title, i.alias, i.catid, i.created, 
     LEFT(i.introtext,1000) fulltext, 
     c.name category 
     FROM {$perfix}_k2_items i 
     INNER JOIN {$perfix}_k2_categories c 
     ON i.catid = c.id 
     WHERE i.featured = '1'"; 
+0

謝謝。我嘗試使用表別名! –