2012-03-14 65 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