2

有什么方法可以转换

$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。但是他们没有为我的问题提供任何正确的答案。

4

2 回答 2

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);
于 2012-08-21T16:56:34.270 回答
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);
于 2017-08-27T23:37:09.197 回答