Need some help - Checking is record exists before adding

Discussion in 'PHP' started by simnorwebdesign, Jan 27, 2008.

  1. #1
    Hi, I am trying to check if a username already exists in the username column of a table and if it does it throws up an error, if it doesn't then it adds the record, I am using the following code:

    <?php
    $con = mysql_connect("localhost","database","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db("database", $con);
     
    $userexists = "SELECT * FROM profile WHERE username='$_POST[username]'";
    
    $num = mysql_num_rows($userexists);
    
    if (!$num > 0)
    {
    	$sql="INSERT INTO profile (username, name, websiteURL, contactDetails)
    VALUES
    ('$_POST[username]','$_POST[name]','$_POST[websiteURL]','$_POST[contactDetails]')";
    
    echo "Your profile has been added";
    
    
    }
    elseif($num == 0)
    {
    echo "Username already in use";
    }
    
    mysql_close($con)
    
    
    ?>
    Code (markup):
    but it doesn't seem to be working, it says the profile has been added but when i look in the database there is no profile.

    Any help would be much appreciated, thank you

    Simon North
     
    simnorwebdesign, Jan 27, 2008 IP
  2. HoagieKat

    HoagieKat Peon

    Messages:
    87
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    change
    
    $userexists = "SELECT * FROM profile WHERE username='$_POST[username]'";
    
    PHP:
    to
    
    $userexists = mysql_query("SELECT * FROM profile WHERE username='$_POST[username]'");
    
    PHP:
     
    HoagieKat, Jan 27, 2008 IP
  3. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #3
    
    if (!$num > 0)
    
    PHP:
    Should be:

    
    if ($num == 0){
    
    PHP:
    And

    
    elseif($num == 0)
    
    PHP:
    Should be

    
    elseif($num > 0)
    
    PHP:
    And change

    
    echo "Your profile has been added";
    
    PHP:
    To

    
    mysql_query($sql);
    echo "Your profile has been added";
    
    PHP:
    Jay
     
    jayshah, Jan 27, 2008 IP
  4. simnorwebdesign

    simnorwebdesign Peon

    Messages:
    595
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks, that worked brilliantly.
     
    simnorwebdesign, Jan 27, 2008 IP