我有一个变量,例如this is a sentence
的句子。我有一个MySQL数据库,其中包含一行包含以下内容的行:
"random sentences"
"few random words"
"this is cool"
"a car"
"nice placement"
我需要打印出数据库行中存在的句子中出现的任何单词。对于上面给出的例句,结果将是:
"random sentences"
"this is cool"
"a car"
这是我到目前为止所尝试的:
<?php
$servername = "localhost";
$username = "dsfdsfds";
$password = "sdfdfsdsf";
$dbname = "sdf";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$galleries = "This is a sentence";
$sql = "
SELECT *
FROM rawwords
WHERE origin LIKE '%" . $galleries. "%'
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - location: " . $row["sentence"]. " <br><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
答案 0 :(得分:0)
创建正确的sql:D
$galleries ="This is a sentence";
$arr = explode(" ", $galleries);
$sql = "SELECT * FROM rawwords WHERE origin LIKE";
$lenght = count($arr);
for ($i=0; $i<$lenght; $i++) {
if ($i == 0) {
$sql .=" '% " . $arr[$i]. " %'";
} else {
$sql .=" or '% " . $arr[$i]. " %'";
}
}
答案 1 :(得分:0)
您可以使用REGEXP
使用[[:<:]]word[[:>:]]
(字边界)来判断句子中的单词。您可以拆分字符串以获取单词,然后使用array_map()
转换它们以进行查询。最后,您可以将implode()
与" or "
胶水一起使用:
$galleries = "This is a sentence" ;
$words = preg_split('~\W~', $galleries, -1, PREG_SPLIT_NO_EMPTY);
$words = array_map(function($word) {
return ' origin REGEXP "[[:<:]]'.$word.'[[:>:]]" ';
}, $words);
$where = implode(' OR ', $words);
$sql = "SELECT * FROM rawwords WHERE $where";
将生成查询:
SELECT * FROM rawwords
WHERE origin REGEXP "[[:<:]]This[[:>:]]"
OR origin REGEXP "[[:<:]]is[[:>:]]"
OR origin REGEXP "[[:<:]]a[[:>:]]"
OR origin REGEXP "[[:<:]]sentence[[:>:]]"
重要,您应该仔细查看参数化查询 请阅读本文,其中包含几个示例:How can I prevent SQL injection in PHP?