Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql_real_escape_string with Zend

I am developing a web application using zend framework. For select statements I have used following way.

Ex:

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

This works fine. But If I send customer name as : colvin's place, The query fail. And I know it's because of the single quote.

Earlier I used addslashes PHP function. But I saw it is not a good way to do this. This time I used mysql_real_escape_string PHP function.

The issue is it says following warning.

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)

This is because of the mysql_real_escape_string function needs a connection to the database opened by mysql_connect. My question is how can I use this with *Zend_DB* classes. I need to use custom select queries always. Appreciate your other suggestions if available.

Thank you

like image 594
Prasad Rajapaksha Avatar asked Dec 31 '11 02:12

Prasad Rajapaksha


2 Answers

You can use the quote() function provided by Zend_Db:

http://framework.zend.com/manual/en/zend.db.adapter.html#zend.db.adapter.quoting.quote

like image 94
leepowers Avatar answered Sep 28 '22 06:09

leepowers


You could use parameter binding as well, then the method will look like:

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

Then your data will be escaped automatically

like image 34
A. Martyn Avatar answered Sep 28 '22 08:09

A. Martyn