php PDO MySQL查询中LIKE的GET值的bindParam [重复]

8ljdwjyq  于 2022-12-10  发布在  PHP
关注(0)|答案(2)|浏览(203)

此问题在此处已有答案

How do I create a PDO parameterized query with a LIKE statement?(9个答案)
3小时前关门。
有没有办法

$term = $_GET['p'];
$stmt = $dbh->prepare("
    SELECT      *
    FROM        posts
    WHERE       heading LIKE '%$term%'
    OR          full_text LIKE '%$term%'
    LIMIT       0 , 30
");
$stmt->execute();
$answer = $stmt->fetch(PDO::FETCH_ASSOC);

转换成类似于

$term = "'%" . $_GET['p'] . "%'";
$stmt = $dbh->prepare("
    SELECT      *
    FROM        posts
    WHERE       heading LIKE :term
    OR          full_text LIKE :term
    LIMIT       0 , 30
");
$stmt->bindParam(":term", $term);
$stmt->execute();
$answer = $stmt->fetch(PDO::FETCH_ASSOC);

以便在查询中使用bindParam(":term", $term);而不是'%$term%'
我已经看过这些Using LIKE in bindParam for a MySQL PDO QueryMysql, PDO - Like statement not working using bindParam,但是它们没有给予我任何正确的答案。

dced5bon

dced5bon1#

将通配符连接到SQL中的变量:

$stmt = $dbh->prepare("
    SELECT      *
    FROM        posts
    WHERE       heading   LIKE CONCAT('%', :term, '%')
    OR          full_text LIKE CONCAT('%', :term, '%')
    LIMIT       0 , 30
");
$stmt->bindParam(':term', $_GET['p']);
$stmt->execute();
$answer = $stmt->fetch(PDO::FETCH_ASSOC);
sczxawaw

sczxawaw2#

您只需要%。不要使用'(简单的queto)
例如:

$term = "'%" . $_GET['p'] . "%'";
$stmt = $dbh->prepare("
    SELECT      *
    FROM        posts
    WHERE       heading LIKE :term
    OR          full_text LIKE :term
    LIMIT       0 , 30
");
$termWithQueto = "%".$term."%";
$stmt->bindParam(":term", $termWithQueto, PDO::PARAM_STR);
$stmt->execute();
$answer = $stmt->fetch(PDO::FETCH_ASSOC);

相关问题