Reputation: 1
I have a script that checks if a record exists before inserting a new record into the database:
if(mysql_num_rows(mysql_query("select post_url from vinanghinguyen_posts where post_url = '$final_url'")) < 1)
{
//insert
}
If post_url
is already in the database then do not insert. I check in database. I have some post_url
like $final_url
but it still inserts normally. Why?
Upvotes: 0
Views: 943
Reputation: 42140
A better way to do this would be to enforce the uniqueness of post_url
in your schema by adding a unique key.
CREATE UNIQUE INDEX vinanghinguyen_posts_unique_url
ON vinanghinguyen_posts( post_url )
Now you can make the database do the work by telling it to ignore duplicate entries
//clean the data
$final_url = mysql_real_escape_string( $final_url );
mysql_query( "INSERT IGNORE INTO
vinanghinguyen_posts
VALUES
('$final_url')" );
Upvotes: 0
Reputation: 18016
just check true and false condition
if(mysql_num_rows(mysql_query("select post_url from vinanghinguyen_posts where post_url = '$final_url'")))
{
//insert
}
Upvotes: 0
Reputation: 7675
Use "== 0
" in replace of "< 0
" in if condition. The total number of rows in database will never less than 0, it must be 0 or greater than 0. And one more thing never use =
for check operator use ==
if(mysql_num_rows(mysql_query("select post_url from vinanghinguyen_posts where post_url = '$final_url'")) == 0)
{
//insert
}
Upvotes: 2