PDO“喜欢"查询 [英] PDO 'LIKE' query

查看:74
本文介绍了PDO“喜欢"查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我是刚开始使用PDO并在从简单的选择查询中偏离时遇到问题,所以我想最好在这里问一下.

Since I'm new to using PDO and running into a problem when deviating from a simple select from query, I figured I'd best ask around here.

代码:

  $sDbase = str_replace('`', '', $modx->db->config['dbase']);
  $oPdo = new PDO("mysql:host=localhost;dbname=" . $sDbase . ";",   $modx->db->config['user'], $modx->db->config['pass']);
  $oPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  if(isset($_POST["search"]))
  {
    $sSearch = (!empty($_POST["search"])) ? mysql_real_escape_string($_POST["search"]) : "" ;
  }

  $sSearch = 'beer' ;

  $sQry = <<< QRY
    SELECT
      contentid AS standid
      ,value AS found
      ,pagetitle
      ,published
    FROM 
      modx_site_tmplvar_contentvalues
    RIGHT JOIN
      modx_site_content
      ON
      modx_site_content.id = modx_site_tmplvar_contentvalues.contentid
    WHERE
      ( tmplvarid = 41 OR tmplvarid = 40 )
    AND
      (value LIKE '%:search%'
      OR
      pagetitle LIKE '%:search%')
    AND
      published = '1'
    ORDER BY
      pagetitle
    ASC
QRY;

  $oRes = $oPdo->prepare( $sQry );
  $oRes -> bindParam( ":search", $sSearch );
  $oRes -> execute() ;

  $aRow = $oRes->fetchAll();
  $oRes -> closeCursor();


  var_dump($aRow);

变量$sSearch是我要绑定到查询中的:search的对象.对于此示例,我已经在其中设置了一个值,但是显然我想用POST变量替换它,这就是为什么我想首先使用PDO的原因.

The variable $sSearch is what I want to bind to :search in the query. For this example, I've set a value in it, but obviously I want to replace that with a POST variable which is why I want to use PDO in the first place.

但是,该查询已经用$sSearch替换为某些searchvalue进行了测试,并且可以正常工作,但是现在我使用PDO来执行相同的查询,但结果为空.好吧,真的是一个空数组.

However, the query has been tested with $sSearch replaced by some searchvalue and works, but now I've used PDO to perform the same query, and I get a blank result. Well, an empty array really.

那我在这里想念什么?

推荐答案

每个Amelia的评论,这是答案:

Per Amelia’s comment, here is the answer:

$sSearch = '%bier%' ;

value LIKE :search

成功了!

这篇关于PDO“喜欢"查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆