How to write a SQL Safe Query using quoteInto() method magento 2?

Using a SQL quoteInto() method, Write a Query using Magento standard way with SQL Safe quoted value.

You can avoid SQL injection attacks, no matter which database you use, is to separating the data value from the SQL statement. You can use ? to pass data in SQL query with the quoteInto() method.

Return Type: Always returns a string with SQL-safe quoted value placed into the original text.

You can use a given method in the direct SQL query for a safe quote with SQL conditions.

Base Definition:

/*
 * @param string $text The text with a placeholder.
 * @param mixed $value The value to quote.
 * @param string $type OPTIONAL SQL datatype
 * @param integer $count OPTIONAL count of placeholders to replace
 * @return string An SQL-safe quoted value placed into the original text.
 */
public function quoteInto($text, $value, $type = null, $count = null);
  • Use of quoteInto() method will be mostly seen inside Direct SQL queries with conditional statements.

Quotes a value and places into a piece of text at a placeholder. The placeholder is a question-mark; all placeholders will be replaced with the quoted value.

For example to delete entries from the core_config_data table with Direct query delete() with the use of quote Into statement,

<?php
namespace Your\PathTo\Model;

use Magento\Framework\App\ResourceConnection;

class UseQuoteIntoSql
{

    private const CORE_CONFIG_TABLE = 'core_config_data';

    private ResourceConnection $resourceConnection;

    public function __construct(
        ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * Delete CoreConfig Entry Query
     *
     * @return $this
     */
    public function deleteCoreConfigEntry()
    {
        $connection  = $this->resourceConnection->getConnection();
        $tableName = $connection->getTableName(self::CORE_CONFIG_TABLE);

        $path = "pathname";
        $scope = "store";
        $scopeId = [0,1];

        $connection->delete(
            $tableName,
            [
                $connection->quoteInto('path = ?', $path),
                $connection->quoteInto('scope = ?', $scope),
                $connection->quoteInto('scope_id IN(?)', $scopeId)
            ]
        );
        return $this;
    }
}

Using the above way, You can use quoteInto() method in a text string with a safe SQL query.