我正在编译这个脚本,它匹配数组中的所有当前单词和数据库,并打印它是否存在于数据库中。
这是脚本:
<?php
$mysqli=new mysqli("127.0.0.1","root","password","database");
$array=
array(
'quick',
'brown',
'fox',
'abc123'
);
$result=$mysqli->query("SELECT `word` FROM `table`");
while ($row=$result->fetch_assoc())
{
$words=$row['word'];
foreach ($array as $value)
{
if (strpos($value,$words)!== false)
{
echo $value." contains a word from the database!\n<br>";
}
}
}
$mysqli->close();
?>
但它不断重复数组中的最后一个元素。 我哪里出错了?
输出:
quick contains a word from the database!
brown contains a word from the database!
fox contains a word from the database!
abc123 contains a word from the database!
abc123 contains a word from the database!
abc123 contains a word from the database!
abc123 contains a word from the database!
abc123 contains a word from the database!
答案 0 :(得分:2)
变化
strpos($value,$words)!== false
要
preg_match('/\b'.$value.'\b/', $words)
strpos搜索一切。如果您在数据库中搜索 abc123 并且它存在,但如果您还有 1,2,3 的值存储在数据库中,它将打印您的原因值重复的价值输出。
答案 1 :(得分:0)
if (strpos($value,$words)!== false)
$words
是一个数组。
答案 2 :(得分:0)
change $words[] = $row['word'];
到
$words = $row['word'];