PHP PDO 预准备语句 -- MySQL LIKE query

2022-08-30 12:02:39

我正在尝试通过php的PDO类(mysql驱动程序)进行搜索。我有以下查询使用MySQL客户端(表名称已更改以保护无辜者):

SELECT    hs.hs_pk, 
          hs.hs_text, 
          hs.hs_did, 
          hd.hd_did, 
          hd.hd_text, 
          hv.hv_text, 
          hc.hc_text 
FROM      hs 
LEFT JOIN hd 
 ON       hs.hs_did = hd.hd_did 
LEFT JOIN hd 
 ON       hd.hd_vid = hv.hv_id 
LEFT JOIN hc 
 ON       hd.hd_pclass = hc.hc_id
WHERE     hs.hs_text LIKE "%searchTerm%"
LIMIT 25;

这与超级按钮一样工作,无论我使用哪个搜索词。但是,当我移动到php时,我无法让它返回任何内容。我已经尝试了几种不同的语法,这些语法似乎合乎逻辑地起作用,但我尝试过的语法都不起作用。这是我现有的代码:

$handle = fopen('/foo/bar/test.log', 'w+');
fwrite($handle, "doSearch, with search term: $searchTerm\n");
$sql = 
'SELECT   hs.hs_pk, 
          hs.hs_text, 
          hs.hs_did, 
          hd.hd_did, 
          hd.hd_text, 
          hv.hv_text, 
          hc.hc_text 
FROM      hs 
LEFT JOIN hd 
 ON       hs.hs_did = hd.hd_did 
LEFT JOIN hd 
 ON       hd.hd_vid = hv.hv_id 
LEFT JOIN hc 
 ON       hd.hd_pclass = hc.hc_id
WHERE     hs.hs_text LIKE :searchTerm
LIMIT 25';

try {
 $dbh = new PDO('mysql:host=localhost;dbname=awdb', "user", "password");
 fwrite($handle, "connected to DB\n");
 $prep = $dbh->prepare($sql);
 $ret = $prep->execute(array(':searchTerm' => '"%'.$searchTerm.'%"'));

 while ($row = $prep->fetch(PDO::FETCH_ASSOC)) {
  $i++;
  $result[$i]['subText'] = $row['hs_pk'];
  $result[$i]['subText'] = $row['hs_text'];
  $result[$i]['subDid'] = $row['hs_did'];
  $result[$i]['devDid'] = $row['hd_did'];
  $result[$i]['devText'] = $row['hd_text'];
  $result[$i]['vendorText'] = $row['hv_text'];
  $result[$i]['classText'] = $row['hc_text'];
 }
    $dbh = null;
}   
catch (PDOException $e) {
  print "Error!: " . $e->getMessage() . "<br/>";
  die();
}

我也尝试了以下方法(SQL WHERE子句和prep->execute行都是这些变化):

WHERE hs.hs_text LIKE CONCAT(\'%\', ?, \'%\') 
$ret = $prep->execute(array($searchTerm));

WHERE hs.hs_text LIKE "%:searchTerm%" 
$ret = $prep->execute(array(':searchTerm' => $searchTerm));

WHERE hs.hs_text LIKE ":searchTerm" 
$ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));

等。。。


答案 1
$ret = $prep->execute(array(':searchTerm' => '"%'.$searchTerm.'%"'));

这是错误的。您不需要双引号。

WHERE hs.hs_text LIKE ":searchTerm" 
$ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));

这也是错误的。尝试使用:

$prep = $dbh->prepare($sql);
$ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));

说明: 预准备语句不只是执行字符串替换。它们将数据与查询完全分开传输。仅当将值嵌入到查询中时,才需要引号。


答案 2
$prep = $dbh->prepare($sql);
$ret = $prep->execute(array('searchTerm' => $searchTerm));

推荐