How can i check for duplicate entry before i insert?

Discussion in 'PHP' started by baris22, Jan 20, 2009.

  1. #1
    hello,

    I am using this code to insert into database:

    
    $query="INSERT INTO `web` VALUES ('', '".$titleweb."', '".$user_no."')";
    mysql_query($query);
    	
        echo mysql_error();
        $c++;
       }
      }
    
    PHP:
    I do not want to insert dublicate entries. If I have an entry in ".$user_no." I do not want to have the same entry.

    forexample this is my database:

    id titleweb user_no
    1 test 13
    2 yyu 18
    3 rfrf 21

    If i want to insert an entry with user_no 13 it should not let me enter because i`ve already have one in database.
     
    baris22, Jan 20, 2009 IP
  2. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #2
    you can change the field in your table to be unique and then the query won't be inserted.

    if you don't, just do a query before for getting the user id and check if it exists..
     
    yoavmatchulsky, Jan 20, 2009 IP
  3. jonhel

    jonhel Peon

    Messages:
    26
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Use a SELECT query and then the PHP mysql_num_rows function, such as this:-

    $result = mysql_query ("SELECT * FROM tablename WHERE user_no  = 'whatever');
    $num_rows = mysql_num_rows($result);
    
    // They already have a user number
    
    if ($num_rows > '0')
    {
    Do this
    }{
    Code (markup):
    Hope this helps,


    Jonathan
     
    jonhel, Jan 20, 2009 IP
  4. Pos1tron

    Pos1tron Peon

    Messages:
    95
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Don't do this - it's a waste of a query. Even if you did need do that, you'd probably be better using COUNT in the sql syntax to save on calling mysql_num_rows.

    Do what this yoavmatchulsky said - it's far more efficient.
     
    Pos1tron, Jan 20, 2009 IP
  5. baris22

    baris22 Active Member

    Messages:
    543
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    60
    #5
    Thank you for the replies. I decided to make that field unique. it will be much easier for future.

    thanks again

     
    baris22, Jan 20, 2009 IP