pdo使用like搜索数据库

4ktjp1zp  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(390)

我尝试使用以下代码创建一个小型搜索函数来查看数据库:

$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';
}

这将返回数据库中的所有项,而不仅仅是相似的项,
然后我运行了以下sql查询:

SELECT * FROM topic WHERE topic_name LIKE '%Li%';

它按预期运行并返回所需的结果。
我错过了什么?

rur96b6h

rur96b6h1#

从占位符中删除引号,并在绑定引用之前添加冒号:

$query = $connDB->prepare('SELECT * FROM topic WHERE topic_name LIKE :keywords');
$query->bindValue(':keywords', '%' . $searchQ . '%');

下面是我的文本示例:

sql语句

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');

PHP

$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>";
}

输出

Array
(
    [id] => 1
    [name] => apple
)
Array
(
    [id] => 3
    [name] => grape
)
snvhrwxg

snvhrwxg2#

您需要将单个变量传递给 bind_param 不是一个 concatenated 字符串,因为参数 two 必须是引用而不是值。

$keyword_to_search = '%' . $searchQ . '%';
$query->bindValue('keywords', $keyword_to_search);
o4hqfura

o4hqfura3#

只能绑定数据文本。尝试

$searchQ = '%Li%'; OR  $searchQ = '%'.Li.'%';
$query = $connDB->prepare('SELECT * FROM topic WHERE topic_name LIKE :keywords');
$query->bindValue('keywords', $searchQ );
af7jpaap

af7jpaap4#

showdev谢谢你的教程

sql语句

CREATE TABLE IF NOT EXISTS 'news' 
(`id` int(9) NOT NULL auto_increment, 
  `title` text NOT NULL, 
  PRIMARY KEY  (`id`)
) 
ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
insert into `items` (`id`, `title`) VALUES
(1, 'news title'),
(2, 'news title 2');

PHP

$connection = new PDO('mysql:host=localhost;dbname=YOUR_DATABASE_NAME','root','');
if (isset($_GET['store'])) {
$store = $_GET['store'];
if(!empty($store)){//condition you the remove karakter
    $q=$connection->prepare("SELECT title FROM tbl_nes WHERE title LIKE :store");
    $q->bindValue(':store','%'.$store.'%'); 
    $q->execute();
    while ($r = $q->fetch(PDO::FETCH_OBJ)) { 
        echo $r->title,"<br>";
    }         
}
}

输出

1.news title
2.news title 2 ....

相关问题