2011-12-31 58 views
5

我正在开发一个使用zend框架的web应用程序。对于select语句,我使用以下方法。与Zend的mysql_real_escape_string

例:

public function getData($name) 
{ 
    $sql = "SELECT * from customer where Customer_Name = '$name'"; 
    return $this->objDB->getAdapter()->fetchAll ($sql); 
} 

这工作得很好。但是,如果我将客户名称发送为:colvin's place, 查询失败。我知道这是因为单引号。

早些时候我用addslashes PHP函数。但我看到这不是一个好办法。这次我使用了PHP功能mysql_real_escape_string

问题是它说下面的警告。

Warning</b>: mysql_real_escape_string() [<a href='function.mysql-real-escape-string'>function.mysql-real-escape-string</a>]: Access denied for user 'ODBC'@'localhost' (using password: NO)

这是因为mysql_real_escape_string功能需要通过mysql_connect打开数据库的连接。我的问题是我如何使用* Zend_DB *类。我需要始终使用自定义选择查询。欣赏你的其他建议,如果可用。

谢谢

+1

没哟尝试使用[Zend_DB_Statement](http://framework.zend.com/manual/ en/zend.db.statement.html) – 2011-12-31 02:23:46

+0

感谢Shiplu。我会查的。 – 2011-12-31 02:24:44

+1

我使用addslashes()和整数Intval()。但使用addslashes是一种不好的做法。 – devOp 2012-07-31 14:03:24

回答

1

我有同样的问题,这个解决方案工作正常,我。我希望这将有所帮助。 你可以做这样的事情:

$quote_removed_name = str_replace("'","''",$name); 

然后再编写查询这样:

$sql = "SELECT * from customer where Customer_Name = '$quote_removed_name'"; 
+0

你如何确保没有其他需要转义的角色? 'mysqli_real_escape_string()'知道它们全部,并且它们依赖于数据库连接的编码设置。 – Sven 2012-10-11 08:01:00

+0

此外,你并不总是想要删除引号(因为你的实际操作)。你提出的解决方案不是解决问题,而是解决问题的一部分。 – TheMonarch 2013-11-14 23:33:44

2

你可以使用参数绑定为好,则该方法将看起来像:

public function getData($name) 
{ 
    $sql = "SELECT * from customer where Customer_Name = :name"; 
    return $this->objDB->getAdapter()->fetchAll ($sql, ['name' => $name]); 
} 

然后你的数据会自动转义出

0

我有这个问题,我用这种方式d工作正常:

可以使用quote()

报价()方法接受一个参数,标量字符串值。它以特殊字符的形式返回值,这些字符以适用于您正在使用的RDBMS的方式进行转义,并由字符串值分隔符包围。标准的SQL字符串值分隔符是单引号(')。

但报价返回一个字符串“字符串”(返回它的内部报价单),例如我得到一个字符串从用户从输入文本框(或由GET方法URL)

$string = $this->parameters['string']; // This is like $_POST or $_GET 
$string = $this->db->quote($string); 
$string = substr($string, 1, strlen($string)-2); 
//The above line will remove quotes from start and end of string, you can skip it 

现在我们可以使用这个$string,它是像什么mysql_real_escape_string回报

+0

为什么不简单修剪($ this-> db-> quote($ string),'“\'”); – 2017-09-05 14:26:16