如何使用quoteInto()方法magento2 编写SQL安全查询?

使用 SQL quoteInto()方法,使用 Magento 标准方式和 SQL 安全引用值编写查询。

返回类型:quoteInto() 总是返回一个带有 SQL 安全引用值的字符串,该值放置在原始文本中。

在直接 SQL 查询中使用的quoteInto()方法用于使用 SQL 条件进行安全引用。

基本定义:

/*
 * @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);
  • quoteInto()方法的使用主要出现在带有条件语句的 Direct SQL 查询中。

引用一个值并将其放入占位符的一段文本中。占位符是一个问号;所有占位符都将替换为引用的值。

使用直接查询 delete()从core_config_data表中删除条目的示例,

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class UseQuoteInto {

    const CORE_CONFIG_TABLE = 'core_config_data';

    /**
     * @var ResourceConnection
     */
    private $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 = 1;

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

Using the above way, You can use quoteInto() method into text string with Safe SQL query.

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论