简体   繁体   English

PHP句子搜索-在句子中搜索关键字(MySQL)

[英]PHP Sentence Search - search keywords (MySQL) in a sentence

In general, keywords are searched in MySQL field, for example; 通常,例如,在MySQL字段中搜索关键字。

[tbl_hp] id, title [tbl_hp] ID,标题

1, Harry Potter and the Philosopher's Stone
2, Harry Potter and the Chamber of Secrets
3, Harry Potter and the Prisoner of Azkaban
4, Harry Potter and the Goblet of Fire
5, Harry Potter and the Order of the Phoenix
6, Harry Potter and the Half-Blood Prince
7, Harry Potter and the Deathly Hallows

PHP 的PHP

$keyword = "Philosopher";
$keyword = "Harry Potter";

SQL 的SQL

SELECT `id` FROM `tbl_hp` WHERE `title` LIKE '%" . $keyword . "%';

Then results are; 然后结果是:

"Philosopher" => 1
"Harry Potter" => 1,2,3,4,5,6,7

But how to do this? 但是该怎么做呢?

[tbl_hp_keywords] id, keyword [tbl_hp_keywords] ID,关键字

1, philosopher
2, chamber
3, azkaban
4, goblet
5, phoenix
6, prince
7, hallows
8, prisoner
9, Prisoner of Azkaban
10, Half-Blood Prince

PHP 的PHP

$keyword = "Harry Potter and the Chamber of Secrets";
$keyword = "Harry Potter and the Prisoner of Azkaban";
$keyword = "Harry Potter and the Half-Blood Prince";

Then results are; 然后结果是:

"Harry Potter and the Chamber of Secrets" => 2
"Harry Potter and the Prisoner of Azkaban" => 3,8,9 => or even better result is 9
"Harry Potter and the Half-Blood Prince" => 6,10 => or even better resurt is 10

Any help or ideas on how to do this... Thanks in advance :) 有关如何执行此操作的任何帮助或想法...预先感谢:)

<?php
$keywords = explode(' ', $keyword);
foreach($keywords AS $key){
    $sql = "SELECT id FROM tbl_hp_keywords WHERE keyword = '$key'";
    $query = mysql_query($sql);
    while($result = mysql_fetch_array($query)){
        $ids[] =$result['id'];
    }
}
$answer[$keyword] = implode(',', $ids);

or try this one 或尝试这个

$keyword = 'Harry Potter and the Chamber of Secrets';
$keywords = explode(' ', $keyword);
$modifiedKeyword = implode("', '", $keywords);
$sql = "SELECT id FROM tbl_hp_keywords WHERE keyword IN ('$modifiedKeyword')";
try {
    $hostname = 'servername';
    $dbname = 'dbname';
    $username = 'username';
    $pw = "password";
    $pdo = new PDO("mssql:host=$hostname;dbname=$dbname", $username, $pw);
} catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
}
$query = $pdo->prepare($sql);
$query->execute();

for ($i = 0; $row = $query->fetch(); $i++) {
    $ids[] = $row['id'];
}

unset($pdo);
unset($query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM