I’m going create database table badwords to store some unwanted words [id,word] as following.
CREATE TABLE `badwords`(
`id` int(3) NOT NULL auto_increment,
`word` text,
PRIMARY KEY (`id`),
KEY `id` (`id`))
let say i’ve stored the following words
(1,ugly)
(2,yak)
Now my visitors might post some links contains one of those bad words and i’m willing to use something like this.
$user = "http://www.this_ugly_site.com"; // visitor post this (ugly) word within
// i'm gonna try to find any of bad words stored in my table
$qry="select * from badwords where word='$user'"; // how to do it (find)
$result=mysql_query($qry) or die($qry);
if(mysql_num_rows($result)=='0'){
echo "Good URL";
}else{
while($line=mysql_fetch_array($result)){
echo "Bad URL";
}}
I do not know how to apply strpos and if it really good solution or there is something else i can use !
or can i use
$qry="select * from badwords where word LIKE '%$user%'";
but it looks un-secure as it embedded a user-provided value into your SQL
so any idea or help how to do it ~ thanks
You’ve asked 3 separate questions:
How do I use
strpos()It’s a native PHP function that takes three parameters. I’d encourage you to use and learn the PHP Docs. Nonetheless, here is an example:
Is there a better way?
Likely. But what you have isn’t bad.
strpos()is one of the faster string functions. If you had thousands of bad words and a large amount of requests per second, then you’d likely want to look into caching the bad words instead of querying MySQL every time. However, no need to prematurely optimize. For now, fail early. That is when you find a bad word,breakout of the loop.How do you escape a string in MySQL?
I’d encourage you to use the MySQLi extension and then
mysqli->real_escape_string().For example: