5

using SQL queries is good practice in Magento 2

over ORM

which is best one to while

customizing

1)Security 
2)Speed

ORM vs SQL queries

which one giving Security and speed

while working with the database magento 2.

anyone explain

Thanks in advance.

2 Answers 2

6

SQL queries are not recommended in Magento official Documentaion.

  • You can get a result in fastly while executing SQL queries, but it affects security.

Avoid raw SQL queries

  • Raw SQL queries can lead to potential security vulnerabilities and database portability issues.
  • Use data adapter capabilities (Magento\Framework\DB\Adapter\Pdo\Mysql by default) to build and execute queries and move all data access code to a resource model.
  • Use prepared statements to make sure that queries are safe to execute.

Refer: https://devdocs.magento.com/guides/v2.3/ext-best-practices/extension-coding/security-performance-data-bp.html

Updated answer:

Prevent Magento SQL Injection – Use Prepared Statements

The alternate option to dynamic queries is the prepared statements. These are the statements which are prepared and parsed later on. So, the database stores the statement without executing it. It first checks the parameters. Later it ensures that a string input is a string only and so on. This ensures that the input is not mischievous. Once all the parameters are checked, it executes the statements. Thus ensuring that no Magento SQL injection attack occurs. Given below is a prepared statement implementation in My SQL and PHP.

Magento uses the Zend framework. So, in that case, the components of the Zend framework can be used. Bind the query parameters to the query with Zend_Db_Select’s bind rather than using a full SQL statement. Like this:

$query = $this->_connection->select()->from('eav_attribute')->where('attribute_id=?', $attributeId); $result = $this->_connection->fetchAll($query);

Magento SQL INJECTION prepared statement

Refer:https://www.getastra.com/blog/cms/magento-security/magento-sql-injection-outcomes-find-and-fix/

4
  • is any tutorials for prepared statements in sql....for magento 2 Commented Jul 18, 2019 at 12:41
  • Check my updated answer @prabhakaran7 Commented Jul 18, 2019 at 14:05
  • thanks and super..... Commented Jul 18, 2019 at 14:41
  • You want to avoid direct queries as they aren't cached. You can end up hammering the database and bringing your server down. I had to learn the hard way. Commented Jul 15, 2020 at 13:33
4

kindly look into it once it will be helpful https://devdocs.magento.com/guides/v2.3/ext-best-practices/extension-coding/security-performance-data-bp.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.