Search code examples
phpformsduplicatesduplicate-data

Simple duplicate word checker in PHP


Is there anyway of detecting a duplicate form submit with PHP?

I have a textfield which is used for typing a one-word phrase into it (eg. "Google"). When the user presses the submit button, the form containing that textfield gets submitted. After that - on the PHP processing page - some data gets selected from a database. If the submitted word doesn't exist, it gets inserted in to the db. But if it already exists, the existing one gets a vote up. This might be a little complicated, but I think it is understandable.

The only problem is that when a user submits something like this: "Google." it gets submitted, although there is already a record that contains "Google".

My question is simple: How can I check for duplicates?

[I already tried out the mysql function: LIKE, but it didn't really work, because when someone submitted something like this: "Goofy" it contained "Goo" in it which is already in the word "Google" -> which is already inserted. ]

So how could I solve this? Is there any good script for it?


Solution

  • While I agree with @Dustin about using the INSERT ... ON DUPLICATE KEY UPDATE you may want to address this issue at the user input level with javascript or PHP during submission rather than having the SQL try and match the strings.

    What are the restrictions of the input field currently. Would you expect users to be using punctuation, number, and other general non-alpha characters?

    example of non-alpha: 1234567890-=()!@#$%^&*_+,./<>?;':"|\
    

    If this is the case I would you a preg_replace or a regExp to remove any of these unwanted characters. Thus removing the problem at is sources.

    Once you have validated/cleansed the input you can use a simple SQL insert like so:

    INSERT INTO table (string, count) VALUES (1,2)
       ON DUPLICATE KEY UPDATE count=count+1;
    

    Hope that helps a little.