title: Check for duplicate user from MySQL database
body: <p>I would like to check for duplicates in a MySQL database when registering an user.</p>
  
  <p>If the user exists display an error to that effect, else sign up.</p>
  
  <p>I know there's a few questions like this but I found it hard to paste any of them into my code.</p>
  
  <pre><code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      //two passwords are the same
      if($_POST['password'] == $_POST['confirmedpassword']) {
  
          $username = $mysqli-&gt;real_escape_string($_POST['username']);
          $password = md5($_POST['password']);
  
          $_SESSION['username'] = $username;
          $_SESSION['password'] = $password;
  
          $sql = "INSERT INTO members(username, password)"
              . "VALUES ('$username','$password')";
  
              //if query is successful redirect to login.php
              if ($mysqli-&gt;query($sql) === true)
                  $_SESSION['message'] = 'Success';
              header("location: login.php");
          } else {
              $_SESSION['message'] = "User couldnt be added";
          }
      } else {
          $_SESSION['message'] = "Passwords dont match";
      }
  }
  </code></pre>