Question

I'm getting compiling this script which it matches all current word in the array and on the database and print if it's existing in the database.

here's the script:

<?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();
?>

but it keeps repeating the last element on the array. where did I go wrong?

output:

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!
Was it helpful?

Solution

change strpos($value,$words)!== false

to preg_match('/\b'.$value.'\b/', $words)

strpos search everything. if you search abc123 on the database and it exist but if you also have the value of 1, 2, 3 stored in the database it will print the value that's why you have repeated value output.

OTHER TIPS

if (strpos($value,$words)!== false)

$words is an array.

change $words[] = $row['word'];

to

$words = $row['word'];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top