我如何创建一个 PDO 参数化查询与象语句?

下面是我的尝试:

$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');


$query->execute(array('value'));


while ($results = $query->fetch())
{
echo $results['column'];
}
112951 次浏览

我一发帖就想出来了:

$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));


while ($results = $query->fetch())
{
echo $results['column'];
}

对于那些使用命名参数的参数,下面介绍如何将 LIKE%部分匹配用于 MySQL 数据库:

WHERE column _ name LIKE CONCAT (’%’,: dangousstring,’%’)

其中命名参数为 :dangerousstring

In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.

编辑: Oracle databases的连接语法使用连接操作符: ||,因此它将简单地变成:

WHERE column_name LIKE '%' || :dangerousstring || '%'

However there are caveats as @bobince mentions here that:

The difficulty comes when you want to allow a literal % or _ character in the search string, without having it act as a wildcard.

So that's something else to watch out for when combining like and parameterization.

$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();


if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}

你也可以试试这个。我也遇到过类似的问题,但是经过研究得到了结果。

$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');


$stmt= $pdo_connection->prepare($query);


$stmt->execute(array(':search' => '%'.$search_term.'%'));


$result = $stmt->fetchAll(PDO::FETCH_ASSOC);


print_r($result);

PDO 转义为“%”(可能导致 sql 注入) : 如果访问者键入字符“%”,在寻找匹配部分字符串 但是时,使用前面的代码将得到所需的结果,即使在数据库中没有存储任何内容(可能导致 sql 注入) ,仍然会得到结果

我已经尝试了很多变化都与同一个结果 PDO 是逃避“%”导致不想要的/不兴奋的搜索结果。

I though it was worth sharing if anyone has found a word around it please share it

这种方法是有效的:

search `table` where `column` like concat('%', :column, '%')

这是我从 幻觉买的

$search = "%$search%";
$stmt  = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();

对我来说很简单。正如他所说,在将其发送到查询之前,必须“首先准备完整的文字”

我有一个类似的需要,但使用变量从一个形式抓取。我这样做是为了使用 PHP 从 PostgreSQL 数据库获得结果:

<?php
$player = $_POST['search'];  //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);


while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>

“ ILIKE”使得搜索不区分大小写,因此搜索购物车、购物车或购物车都将返回相同的结果。

唯一可以让它工作的方法是将% $search% 放入另一个变量中。

    if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
    

$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
        

$stmt->execute(array(':search' => $value));

我不知道这是否是最好的方法,在 while 循环中我使用了:

while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){