0

I have a form which inserts the text (of an article) into a database. When a user submits an article (that has already been submitted) it gets submitted also into the db.

How can I detect a duplicate post (like on stackoverflow)?

Should I select everything from the database and check if the submitted post is like a one before. (I want to post the duplicate alert on the article page as the first comment)

Any help appreciated.

Thanks...

Akos
  • 1,997
  • 6
  • 27
  • 40
  • 1
    You could compare the contents of your database with the article and see if there are any similar records. But that will fail when there is a tiny difference (an extra or left-out character). – Jules Aug 26 '11 at 11:38
  • 1
    The stackoverflow system consists of a (probably really complex) set of match algorithms. It's not easy to copy. If you really want to check for duplicate content, you should have a look at Full Text Search on MyISAM tables in MySQL. – Rijk Aug 26 '11 at 11:54

2 Answers2

2

Create an unique ID, e.g. with uniq_id(), put it in a hidden field within your HTML form, then save it in the database in a field that is set to UNIQUE. When the INSERT operation fails, you know that the POST has already been sent before.

ty812
  • 3,293
  • 19
  • 36
1

If You will have hidden id, that you get from db when try to edit some content, You can use code like this:

if (isset($_POST['id']) && trim($_POST['id']) != '') {
    $query = 'UPDATE table_name
                    SET
                      `key` = \'' .$_POST['key']  . '\'
                    WHERE `id` = \'' . $_POST['id'] . '\'', 0;
  } else {
    $query = 'INSERT INTO table_name
                                  SET
                                `key` = \'' . $_POST['key'] . '\'', 0;
  }
YamahaSY
  • 289
  • 3
  • 17
  • In case anyone sees that and tries to use it, beware that as written it is **wide open to SQL Injection attacks**. If you do this for real, you should use query parameters rather than concatenating the user's input into the SQL. See [How can I prevent SQL injection in PHP?](https://stackoverflow.com/q/60174/157957) – IMSoP Jun 18 '22 at 14:24