Reham Fahmy
Reham Fahmy

Reputation: 5073

error using compare code

If i've database my_table (id,word) as following

my_table (id,word)

and i've some posted text called $name then i want to know if $name have any word like words i've stored in my database my_table (id,word)

so i'm using this code

$name = "Hello lovely world"; // no bad words

$sql    = "SELECT * FROM my_table";
$result = mysql_query($sql);

$commentArray = explode(" ", $name);
$counter      = count($commentArray);
$check        = 0;

while ($row = mysql_fetch_assoc($result)) {

    for ($i == 0; $i < $counter; $i++) {

        if (strcasecmp($commentArray[$i], $row['word'])) {
            $check = 1;
        }

    }

}

if ($check == 1) {
    echo "banned";
    exit;
}
else {
    echo "passed";
}

however it always results in echo "banned"; even if i $name is clear of any bad words i've stored in my_table so there might be something wrong here !

anyhelp

Upvotes: 0

Views: 74

Answers (4)

user1233508
user1233508

Reputation:

As a starting point, I'd suggest storing only lowercased words in the table, lowercasing the input text first, and then replacing the whole strcasecmp loop with an in_array($row['word'], $commentArray);. And break; after the first match.

But this entire approach doesn't scale - you're selecting all the entries in the table. If your table grows beyond a certain size, that will be a serious bottleneck and you'll need to look into matching on the DB side.

Upvotes: 1

Michele Spagnuolo
Michele Spagnuolo

Reputation: 932

strcasecmp returns 0 when it matches (PHP manual), so you should edit your code:

if (strcasecmp($commentArray[$i], $row['word']) == 0)

Furthermore, you have a syntax error in your for loop. It should be for ($i = 0; ...

Upvotes: 3

Mikulas Dite
Mikulas Dite

Reputation: 7941

The thing is strcasecmp returns 0 if the strings are equal. You ought to change it to if (strcasecmp($var1, $var2) == 0).

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

You have a syntax error.

for ($i = 0...

And not

for ($i == 0...

Also, you should indent your code properly, it looks better and it'll help you later on.

Upvotes: 1

Related Questions