1

I'd like to store banned words in a database to later determine if some word is present (hence being a banned word, which should be censored).

Word input form (ban.php) :

<form name="form" method="post" action="add.php">
    <input type="text" name="bad" id="bad">
    <input type="submit" name="submit" id="submit" size="12" value="submit">
</form>

PHP code (add.php) :

<?PHP
require_once("config.php"); // db conn

$bad = $_POST['bad'];
$bad = mysql_real_escape_string($bad);
$sql = "insert into my_table set bad='$bad'";

mysql_query($sql, $conn) or die(mysql_error());
echo "Done bad word added";
?>

Let's say we banned the word ugly. Now I want do this :

<?PHP
require_once("config.php"); // db conn

$qry    = "select * from my_table";
$result = mysql_query($qry) or die($qry);
$test   = "ugly"; // Example

if ($test == any of the words in the db my_table){
    echo "banned";
}else{
    echo "passed";
{
?>

How to do this? There are many added words in my_table :

id,bad (1,'ugly')
id,bad (2,'sick')
id,bad (3,'manal')
id,bad (4,'fog')
user4157124
  • 2,809
  • 13
  • 27
  • 42
Reham Fahmy
  • 4,937
  • 15
  • 50
  • 71

3 Answers3

4

You should attempt to select the word from the database, this is much faster than having to go through an array.

Something like this should work.

<?php
require_once("config.php"); // db conn

$test = "ugly"; // remember to use mysql_real_escape_string in the implementation

$qry = "SELECT * FROM `my_table` WHERE bad='{$test}'"; // select by value
$result=mysql_query($qry);

if( mysql_num_rows( $result ) ){ // we have a row with the 'bad' word
    echo "banned";
}else{
    echo "passed";
}
?>
Robjong
  • 375
  • 1
  • 6
  • I don't see the point of a "select *"- you are pulling back unnecessary data from the query. A select count will yield a single int.. Which may not be a performance issue in a simple application such as this, but in a scaled application it could be – Lock Feb 26 '12 at 11:42
  • 2
    Correct, but that's one of the least problematic things here as I see it. From the code posted I figured the OP is quite new to PHP/MySQL, so I kept it simple and readable. – Robjong Feb 26 '12 at 11:49
3

Use a different SQL statement

$qry = "select * from my_table where bad = '".$test."'";

Than just test the result if there is anything or nothing (banned or passed).

user219882
  • 15,274
  • 23
  • 93
  • 138
2

Your SQL of inserting does not make sense. You are inserting, but using the update syntax. Your query should be "insert into my_table values (1, '$bad');

In terms of looking for a banned word, you are better looking for the bad word through your query:

Select count(1) from my_table where word = banned word.

If you run mysql_num_rows over the query, anything greater than 0 means it is banned.

Lock
  • 5,422
  • 14
  • 66
  • 113