問題描述
由于我剛開始使用 PDO 并且在偏離簡單的 select from 查詢時遇到問題,我想我最好在這里詢問.
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
替換為一些搜索值進行了測試并且可以正常工作,但是現在我已經使用 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.
那么我在這里錯過了什么?
So what am I missing here?
推薦答案
根據 Amelia 的評論,答案如下:
Per Amelia’s comment, here is the answer:
$sSearch = '%bier%' ;
和
value LIKE :search
成功了.
這篇關于PDO 'LIKE' 查詢的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!