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.
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