2012-03-14 62 views
0

編輯:Zend的DB where子句錯誤

查詢 - $>其中( '?`值` =',$號); 看來,這項工作。我仍然不知道爲什麼它在正常情況下無法正常工作,但這是一個解決方法..仍然在尋找正確的答案!


我想查詢一個簡單的一個DB:

$number = 4; 
$query = $this->select(); 
$query->where('value = ?', $number); 
$row = $this->fetchRow($query); 

但由於某些原因我不斷地得到這個錯誤:

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 'value = 4) LIMIT 1' at line 1

當我做我的組裝看查詢字符串:

SELECT `mighty_table`.* FROM `mighty_table` WHERE (value = 4) 

My co lumn的名字不能逃脫..

Zend DB應該這樣做嗎? :|這很奇怪,因爲我在其他項目中使用相同的方法,它總是工作..

+0

'語法錯誤或訪問violation'檢查你有你的連接字符串正確。這可能是由錯誤的用戶名/密碼造成的。 – vascowhite 2012-03-14 16:14:11

+0

@vascowhite讓我的連接工作,那不是問題。 :\ – MGP 2012-03-14 16:17:51

+0

嘗試'$ query-> where(「value ='?',$ number);'。我看不到其他任何可能錯誤的內容 – vascowhite 2012-03-14 16:22:32

回答

1

「值」確實是MySQL中的保留字。因此你需要使用back ticks來逃避它。

我希望這個工作:

$fieldName = $this->getAdapter()->quoteIdentifier('value'); 
$query->where($fieldName = ?", $number); 
3

From zend manual

Note: The values and identifiers in the SQL expression are not quoted for you. If you have values or identifiers that require quoting, you are responsible for doing this. Use the quote(), quoteInto(), and quoteIdentifier() methods of the database adapter.

因此,例如,你可以使用quoteInto:

$number = 4; 
$query = $this->select(); 
$where = $this->getAdapter()->quoteInto('value = ?', $number); 
$query->where($where); 
$row = $this->fetchRow($query); 
+0

這個可能需要 - > quoteIdentifier(),我很確定VALUE是Mysql中的關鍵字,我知道VALUES是。 – RockyFord 2012-03-15 07:43:00

+0

這就是爲什麼我的代碼都是越野車的原因。感謝你的回答! :) – MGP 2012-03-19 16:19:21