37

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

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

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

现在,手册说:

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

我认为不是用 :termX (x for 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
        )
)
4

5 回答 5

25

我现在已经多次遇到同样的问题,我想我找到了一个非常简单和好的解决方案。如果我想多次使用参数,我只需将它们存储到 MySQLUser-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 查询 - 但恕我直言,这是完全值得的。
由于User-Defined Variables在 MySQL 中是会话绑定的,因此也无需担心@term在多用户环境中导致副作用的变量。

于 2015-06-26T08:52:17.293 回答
10

我创建了两个函数来通过重命名重复使用的术语来解决问题。一种用于重命名 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:字符串,n:数字,a:数组,m:混合

于 2014-06-24T13:24:51.837 回答
9

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

您不能在准备好的语句中多次使用同名的命名参数标记,除非仿真模式为 on

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_PREPARESfalse,然后它开始失败。

(PHP 5.4.38,MySQL 5.1.73 FWIW)

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

于 2016-02-13T03:05:07.977 回答
3

一个可行的解决方案:

$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();
于 2013-08-29T13:55:08.393 回答
0

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

//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);
    }
}

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

希望这可以在不久的将来帮助某人。

于 2015-11-23T17:58:40.437 回答