title: MySQL/PHP check for duplicate before INSERT
body: <p>I'm trying to check for an existing entry in MySQL before executing the INSERT statement.  If the user enters a name already in the database (field is set to unique) then they should be prompted to re-enter the name.</p>
  
  <p>The problem I'm having is that if the new entry matches a record in any form then the error message displays and no INSERT happens.  </p>
  
  <p>For example, if the user enters DUMMY_NEW and there is a record DUMMY_OLD they aren't able to add the record even though DUMMY_NEW does not exist in the table.</p>
  
  <p>I've searched and tried other answers already but can't seem to get this to work.</p>
  
  <p>Code with extraneous bits removed for clarity:</p>
  
  <pre><code>//Create connection to database using mysqli
  $conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
  
  //Set variables according to user input on previous form
  $Server_Name = $_POST['Server_Name'];
  
  //Check for duplicate server name - if exists inform user else run INSERT ($stmt)
  $checkdup = "SELECT * FROM dcr_table WHERE SERVER_NAME = '".$Server_Name."'";
  $dupresult = $conn-&gt;query($checkdup);
  
  if($dupresult = 1)
  {
          print "&lt;br&gt;Error! &lt;p&gt;&lt;/p&gt;";
          echo "" . $Server_Name . " already exists in the DCR";
          print "&lt;p&gt;&lt;/p&gt;Please check the Server Name and try again";
  }
  else {
  
  
  //Define the INSERT statement
      $stmt = "INSERT INTO dcr_master (Server_Name, Description,..., ... , ... )";
  
  //Execute the INSERT statement
      $conn-&gt;query($stmt);
  
  //Success and return new id
      echo "&lt;br&gt;&lt;p&gt;&lt;/p&gt;Record Added!&lt;p&gt;&lt;/p&gt;";
      echo "New id: " . mysqli_insert_id($conn);
  
  //Drop the connection
      $conn-&gt;close();
  };
  </code></pre>
  
  <p>Edit:
  I'm aware of the injection vulnerability.  The MySQL account only has SELECT, INSERT and UPDATE rights to the table. The end user must supply the password or submit will fail.  This is small app with limited user access at the moment.  MySQL escape strings will be implemented after current issue is resolved.</p>
  
  <p>Edit 2:
  Using Hobo Sapiens method does work in reporting an existing entry however a new (empty) row is still added to the table.  The record ID still auto-increments so what I get is id#300 - record, id#301 - blank,  id#302 - record.  Is this a result of the IGNORE in the INSERT statement?</p>