How to prevent inserting duplicate database records?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • azura
    New Member
    • Jul 2008
    • 47

    How to prevent inserting duplicate database records?

    how i want to check if there is duplicate entry in my database?? i insert new record which is the same record that i had inserted before,it successfull insert into the database..i don't want that.. what i want is the error must appear when i try to save the same previously record.. can you all help me please... newbie in php..
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    #2
    One solution is for this (may be not the best) is, there you can create a UNIQUE column in your table and when there is a duplicate entry you can trap the error.

    Comment

    • azura
      New Member
      • Jul 2008
      • 47

      #3
      oh that means i have to make one of my data are in unique??

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        Hi.

        I've changed the title of this thread to better describe it's content.
        Please try to give your threads meaningful titles. Bad titles reduce the chance your question will be noticed by those who may be able to help!

        Check out the Posting Guidelines for tips on how to make good thread titles.

        Thanks.

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          Using a UNIQUE key is probably the best way to handle this.
          That way, the Database server itself will prevent duplicate rows from being created, so your PHP application won't have to.
          Although, you will have to make sure your code can detect and handle the error.

          If you already have your table, you could add the UNIQUE key by using the ALTER TABLE syntax.
          Like (assuming MySQL, but would probably work for others to)
          [code=mysql]
          ALTER TABLE tblName ADD UNIQUE (theColumn);
          /* Or if you need multiple columns */
          ALTER TABLE tblName ADD UNIQUE (col1, col2, /*...*/, colN);
          [/code]
          And as always, remember to test this before using it on any data you can't afford to lose.

          Comment

          Working...