多次使用绑定参数


Use bound parameter multiple times

我正在尝试为我的数据库实现一个非常基本的搜索引擎,用户可以在其中包含不同类型的信息。搜索本身由两个联合选择组成,其中结果总是合并到3列中。

然而,返回的数据是从不同的表中提取的。

每个查询都使用$term进行匹配,我已经将其绑定到":term"作为一个准备好的参数。

现在,手册上写着:

在调用PDOStatement::execute()时,必须为要传递给语句的每个值包含一个唯一的参数标记。在准备好的语句中,不能两次使用相同名称的命名参数标记。

我想,与其用:termX(x表示term=n++)替换每个:term参数,还必须有更好的解决方案吗?

或者我只需要绑定X个:termX?

编辑发布我的解决方案:

$query = "SELECT ... FROM table WHERE name LIKE :term OR number LIKE :term";
$term = "hello world";
$termX = 0;
$query = preg_replace_callback("/':term/", function ($matches) use (&$termX) { $termX++; return $matches[0] . ($termX - 1); }, $query);
$pdo->prepare($query);
for ($i = 0; $i < $termX; $i++)
    $pdo->bindValue(":term$i", "%$term%", PDO::PARAM_STR);

好的,这是一个样品。我没有时间使用sqlfiddle,但如果有必要,我稍后会添加一个。

(
    SELECT
        t1.`name` AS resultText
    FROM table1 AS t1
    WHERE
        t1.parent = :userID
        AND
        (
            t1.`name` LIKE :term
            OR
            t1.`number` LIKE :term
            AND
            t1.`status` = :flagStatus
        )
)
UNION
(
    SELECT
        t2.`name` AS resultText
    FROM table2 AS t2
    WHERE
        t2.parent = :userParentID
        AND
        (
            t2.`name` LIKE :term
            OR
            t2.`ticket` LIKE :term
            AND
            t1.`state` = :flagTicket
        )
)

我已经多次遇到同样的问题,我认为我已经找到了一个非常简单和好的解决方案。如果我想多次使用参数,我只需将它们存储到MySQL User-Defined Variable
这使得代码可读性更强,并且您不需要在PHP:中使用任何其他函数

$sql = "SET @term = :term";
try
{
    $stmt = $dbh->prepare($sql);
    $stmt->bindValue(":term", "%$term%", PDO::PARAM_STR);
    $stmt->execute();
}
catch(PDOException $e)
{
    // error handling
}

$sql = "SELECT ... FROM table WHERE name LIKE @term OR number LIKE @term";
try
{
    $stmt = $dbh->prepare($sql);
    $stmt->execute();
    $stmt->fetchAll();
}
catch(PDOException $e)
{
    //error handling
}

唯一的缺点可能是你需要做一个额外的MySQL查询,但imho这完全值得。
由于User-Defined Variables在MySQL中是会话绑定的,因此也不必担心变量@term在多用户环境中会产生副作用。

我创建了两个函数,通过重命名重复使用的术语来解决这个问题。一个用于重命名SQL,另一个用于重新命名绑定。

    /**
     * Changes double bindings to seperate ones appended with numbers in bindings array
     * example: :term will become :term_1, :term_2, .. when used multiple times.
     *
     * @param string $pstrSql
     * @param array $paBindings
     * @return array
     */
    private function prepareParamtersForMultipleBindings($pstrSql, array $paBindings = array())
    {
        foreach($paBindings as $lstrBinding => $lmValue)
        {
            // $lnTermCount= substr_count($pstrSql, ':'.$lstrBinding);
            preg_match_all("/:".$lstrBinding."'b/", $pstrSql, $laMatches);
            $lnTermCount= (isset($laMatches[0])) ? count($laMatches[0]) : 0;
            if($lnTermCount > 1)
            {
                for($lnIndex = 1; $lnIndex <= $lnTermCount; $lnIndex++)
                {
                    $paBindings[$lstrBinding.'_'.$lnIndex] = $lmValue;
                }
                unset($paBindings[$lstrBinding]);
            }
        }
        return $paBindings;
    }
    /**
     * Changes double bindings to seperate ones appended with numbers in SQL string
     * example: :term will become :term_1, :term_2, .. when used multiple times.
     *
     * @param string $pstrSql
     * @param array $paBindings
     * @return string
     */
    private function prepareSqlForMultipleBindings($pstrSql, array $paBindings = array())
    {
        foreach($paBindings as $lstrBinding => $lmValue)
        {
            // $lnTermCount= substr_count($pstrSql, ':'.$lstrBinding);
            preg_match_all("/:".$lstrBinding."'b/", $pstrSql, $laMatches);
            $lnTermCount= (isset($laMatches[0])) ? count($laMatches[0]) : 0;
            if($lnTermCount > 1)
            {
                $lnCount= 0;
                $pstrSql= preg_replace_callback('(:'.$lstrBinding.''b)', function($paMatches) use (&$lnCount) {
                    $lnCount++;
                    return sprintf("%s_%d", $paMatches[0], $lnCount);
                } , $pstrSql, $lnLimit = -1, $lnCount);
            }
        }
        return $pstrSql;
    }

用法示例:

$lstrSqlQuery= $this->prepareSqlForMultipleBindings($pstrSqlQuery, $paParameters);
$laParameters= $this->prepareParamtersForMultipleBindings($pstrSqlQuery, $paParameters);
$this->prepare($lstrSqlQuery)->execute($laParameters);

变量命名说明:
p: 参数,l:函数中的局部
str:string,n:numeric,a:array,m:mixed

我不知道问题发布后它是否发生了变化,但现在查看手册,它说:

在准备好的语句中,不能多次使用相同名称的命名参数标记,除非模拟模式处于

http://php.net/manual/en/pdo.prepare.php——(强调我的。)

因此,从技术上讲,允许使用$PDO_obj->setAttribute( PDO::ATTR_EMULATE_PREPARES, true );进行模拟准备也是可行的;尽管这可能不是一个好主意(正如在这个答案中所讨论的,关闭模拟的准备好的语句是防止某些注入攻击的一种方法;尽管有些人写了相反的文章,认为是否模拟准备对安全性没有影响。(我不知道,但我不认为后者考虑到了前面提到的攻击。)

我添加这个答案是为了完整性;当我在我工作的网站上关闭emulate_prepares时,它导致搜索中断,就像它使用类似的查询(SELECT ... FROM tbl WHERE (Field1 LIKE :term OR Field2 LIKE :term) ...)一样,它工作得很好,直到我明确地将PDO::ATTR_EMULATE_PREPARES设置为false,然后它开始失败。

(PHP 5.4.38,MySQL 5.1.73 FWIW)

这个问题告诉我,不能在同一个查询中使用两次命名参数(这对我来说似乎违反直觉,但哦,好吧)。(尽管我看了很多次那一页,但不知何故,我还是错过了手册中的内容。)

只有启用准备好的语句模拟,才有可能实现。可以通过将PDO::ATTR_EMULATE_PREPARES设置为true来执行此操作。

一个可行的解决方案:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
$query = "SELECT * FROM table WHERE name LIKE :term OR number LIKE :term";
$term  = "hello world";
$stmt  = $pdo->prepare($query);
$stmt->execute(array('term' => "%$term%"));
$data  = $stmt->fetchAll();

用户定义的变量是一种方法,可以在将值绑定到查询时多次使用同一个变量,是的,效果很好。

//Setting this doesn't work at all, I tested it myself 
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);

我根本不想像这里发布的解决方案那样使用用户定义的变量我不想像这里发布的其他解决方案一样进行参数重命名。因此,这是我的解决方案,它不使用用户定义的变量,也不使用较少的代码重命名查询中的任何内容,而且它不关心参数在查询中使用了多少次。我在我的所有项目中都使用了这个,而且效果很好。

//Example values
var $query = "select * from test_table where param_name_1 = :parameter and param_name_2 = :parameter";
var param_name = ":parameter";
var param_value = "value";
//Wrap these lines of codes in a function as needed sending 3 params $query, $param_name and $param_value. 
//You can also use an array as I do!
//Lets check if the param is defined in the query
if (strpos($query, $param_name) !== false)
{
    //Get the number of times the param appears in the query
    $ocurrences = substr_count($query, $param_name);
    //Loop the number of times the param is defined and bind the param value as many times needed
    for ($i = 0; $i < $ocurrences; $i++) 
    {
        //Let's bind the value to the param
        $statement->bindValue($param_name, $param_value);
    }
}

这里有一个简单的工作解决方案!

希望这能在不久的将来帮助到别人。