我想对已查找的搜索字词列表进行索引和排名。我的数据库中有一个单独的表,其中包含以下信息
_ID int Auto_Increment,
TERM varchar(255),
RANK int
我用来获取和显示结果的代码如下
<?php
$q = $_GET['q'];
$DB_NAME = 'code_storage';
$DB_HOST = 'localhost';
$DB_USER = 'user';
$DB_PASS = 'pass';
try {
$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db = new PDO($dsn, $DB_USER, $DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM `snippets` WHERE `CODE_NAME` LIKE :name1 OR `CODE_DESC` LIKE :name2 OR `CODE_TAGS` LIKE :name3 OR `CODE_USAGE` LIKE :name4";
$prep = $db->prepare($query);
$qpattern = "%" . $q . "%";
$prep->execute(array(":name1" => $qpattern, ":name2" => $qpattern, ":name3" => $qpattern, ":name4" => $qpattern));
echo '<div class="row">';
echo '<div class="panel">';
printf("Your search for <b>$q</b> returned %d records.\n", $prep->rowCount());
echo '</div>';
echo '</div>';
while ($row = $prep->fetch()) {
echo ' <div class="row">' . "\n";
echo ' <div class="large-12 columns">' . "\n";
echo ' <b><a href="results.php?id=' . $row['_ID'] . '">' . $row['CODE_NAME'] . '</a></b><br/><br/>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . '<br/>' . "\n";
$db = null;
}
}
catch (PDOException $e) {
echo '<div class="row">';
echo '<div class="panel">';
echo 'Connection failed: ' . $e->getMessage();
echo '</div>';
echo '</div>';
}
?>
我有一个主要问题
编辑:我想通了我刚刚在$ query下添加了这个,现在它可以正常工作
$search = "INSERT INTO `search` (`TERM`, `RANK`) VALUES (:search, 1) ON DUPLICATE KEY UPDATE `RANK` = `RANK` + 1";
$sprep =$db->prepare($search);
$sprep->execute(array(":search" => $q));
答案 0 :(得分:1)
我会从if语句中分离出查询,以便您可以更好地调试它。而不是:
if(!$result = $mysqli->query($sql)){
我愿意:
$result = $mysqli->query($sql);
if($result === false){
然后我会使用查询来插入关键字或更新热门表格中该关键字的排名。请参阅此文章:mysql if exists。我会做这样的事情:
INSERT INTO `popular` (keyword, rank) VALUES ('new keyword', 1)
ON DUPLICATE KEY UPDATE `rank` = `rank` + 1;
假设您将关键字作为主键的一部分,那么如果它不存在则会插入它,如果匹配则增加排名。