我正在尝试使用此代码创建一个小型搜索功能来查看数据库:
$searchQ = 'Li';
$query = $connDB->prepare('SELECT * FROM topic WHERE topic_name LIKE '."':keywords'");
$query->bindValue('keywords', '%' . $searchQ . '%');
$query->execute();
if (!$query->rowCount() == 0) {
while ($results = $query->fetch()) {
echo $results['topic_name'] . "<br />\n";
}
} else {
echo 'Nothing found';
}
Run Code Online (Sandbox Code Playgroud)
这将返回数据库中的所有项目,而不仅仅是相似的项目,
然后我运行了这个SQL查询:
SELECT * FROM topic WHERE topic_name LIKE '%Li%';
Run Code Online (Sandbox Code Playgroud)
这按预期运行并返回所需的结果.
我错过了什么?
sho*_*dev 18
从占位符中删除引号,并在绑定引用之前添加冒号:
$query = $connDB->prepare('SELECT * FROM topic WHERE topic_name LIKE :keywords');
$query->bindValue(':keywords', '%' . $searchQ . '%');
Run Code Online (Sandbox Code Playgroud)
这是我的文字示例:
CREATE TABLE IF NOT EXISTS `items` (
`id` mediumint(9) NOT NULL auto_increment,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `items` (`id`, `name`) VALUES
(1, 'apple'),
(2, 'orange'),
(3, 'grape'),
(4, 'carrot'),
(5, 'brick');
Run Code Online (Sandbox Code Playgroud)
$keyword='ap';
$sql="SELECT * FROM `items` WHERE `name` LIKE :keyword;";
$q=$dbh->prepare($sql);
$q->bindValue(':keyword','%'.$keyword.'%');
$q->execute();
while ($r=$q->fetch(PDO::FETCH_ASSOC)) {
echo"<pre>".print_r($r,true)."</pre>";
}
Run Code Online (Sandbox Code Playgroud)
Array
(
[id] => 1
[name] => apple
)
Array
(
[id] => 3
[name] => grape
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19989 次 |
| 最近记录: |