15

I want to escape string in magento, but when I am using mysql_real_escape_string, i am getting warning.

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.soc.....'

I couldn't find any magento's core mysql escape function. So, what should I do?

swapnesh
  • 26,318
  • 22
  • 94
  • 126
user1463076
  • 2,715
  • 4
  • 16
  • 12
  • Yes, and still googling to find the answer. – user1463076 Jun 21 '12 at 06:47
  • try: http://forums.cpanel.net/f354/cant-connect-local-mysql-server-through-socket-var-lib-mysql-mysql-sock-111-a-78444.html and: http://stackoverflow.com/questions/5376427/cant-connect-to-local-mysql-server-through-socket-var-mysql-mysql-sock-38 – Nir Alfasi Jun 21 '12 at 07:02

2 Answers2

27

Use this to escape a string for a query and add the surrounding single quotes:

Mage::getSingleton('core/resource')->getConnection('default_write')->quote($string);

You can look up Varien_Db_Adapter_Pdo_Mysql for further quoting details if needed.

Vinai
  • 14,162
  • 2
  • 49
  • 69
  • Thanks, this function is escaping string well. It also adds quotes at start and end of string. I hope it will works now. – user1463076 Jun 21 '12 at 07:20
  • 1
    this quote was adding quotes in beginning and at end of string. Then i tested magento without any escaping function and there is no need to escape string. I think magento has default escaping function. my code `($tbl_customer = getMazeTable("customer_entity"); $connection = Mage::getSingleton('core/resource') ->getConnection('core_read'); $select = $connection->select() ->from($tbl_customer) ->where('email=?',$email);) ` – user1463076 Jun 21 '12 at 08:29
  • Yes, you don't need to quote `$email`, `Zend_Db` handles that for you. You can mark it as answered beside the answer you want to accept. – Vinai Jun 21 '12 at 10:22
  • @Vinai any idea if there's any core way to escape characters without quoting? For example, I want to use `\ ` character in a `searchCriteriaBuilder->addFilter()` call, but it needs to be escaped to work correctly. Only escaping method I can see being used in core is `\Zend_Db_Adapter_Abstract::_quote` – Danny Nimmo Jun 23 '21 at 11:28
10

I think Magento uses a DB Access layer based on PDO, which handles escaping automatically provided you use bound parameters. Example from Using Magento Methods to write Insert Queries with care for SQL Injection

$write = Mage::getSingleton("core/resource")->getConnection("core_write");

// Concatenated with . for readability
$query = "insert into mage_example "
       . "(name, email, company, description, status, date) values "
       . "(:name, :email, :company, :desc, 0, NOW())";

$binds = array(
    'name'    => "name' or 1=1",
    'email'   => "email",
    'company' => "company",
    'desc'    => "desc",
);
$write->query($query, $binds);
Community
  • 1
  • 1
siliconrockstar
  • 3,554
  • 36
  • 33