bindParam用于PDO MySQL查询中LIKE的GET值

时间:2012-08-21 16:53:41

标签: mysql pdo get sqlbindparameter sql-like

有没有转换方式

$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);

INTO类似

$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。但他们没有给我任何正确的答案。

2 个答案:

答案 0 :(得分:5)

将通配符符号连接到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);

答案 1 :(得分:0)

你只需要%。不要使用'(简单的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);