title: PHP check if value exists in Database
body: <p>I am using MySQL and I want to check if the value of the users input <code>$_POST['username']</code> already exists in my database (in the field <code>username</code>). I have tried this code:</p>
  
  <pre><code>$usernameExists = "SELECT * FROM users WHERE username = " . $_POST['username'];
  
  if ($usernameExists) {
      echo "Exists"
  } 
  </code></pre>
  
  <p>I put this code after the <code>if (!empty...)</code> statement;</p>
  
  <p>but nothing happened. If you need my full code, it is available here, but I assume the rest of it won't be helpful:</p>
  
  <pre><code>&lt;?php
  
  session_start();
  
  if (isset($_SESSION['user_id'])) { // user is already logged in
      header("Location: index.php");
  }
  
  require('database.php');
  
  $message = '';
  $emailMessage = '';
  $usernameMessage = '';
  $passwordMessage = '';
  $confirmMessage = '';
  
  if (!empty($_POST['email']) &amp;&amp; !empty($_POST['username']) &amp;&amp; !empty($_POST['password']) &amp;&amp; !empty($_POST['confirmPassword'])) { // user submitted form; enter user
  
      if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
          $emailMessage = 'Invalid email.';
  
      } elseif (strlen($_POST['username']) &lt; 4 || strlen($_POST['username']) &gt; 250) {
          $usernameMessage = 'Username has to be between 4 and 250 characters.';
  
      } elseif (!preg_match("/^[a-zA-z0-9]*$/", $_POST['username'])) {
          $usernameMessage = 'Username can only contain numbers and letters.';
  
      } elseif (strlen($_POST['password']) &lt; 6 || strlen($_POST['password']) &gt; 250) {
          $passwordMessage = 'Password has to be between 6 and 250 characters.';
  
      } elseif ($_POST['confirmPassword'] !== $_POST['password']) {
          $confirmMessage = 'Passwords don\'t match THONK';
  
      } else {
          $sql = "INSERT INTO users (email, username, password) VALUES (:email, :username, :password)";
          $stmt = $conn-&gt;prepare($sql);
  
          $stmt-&gt;bindParam(':email', $_POST['email']);
          $stmt-&gt;bindParam(':username', $_POST['username']);
  
          $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
          $stmt-&gt;bindParam(':password', $password);
  
          if ($stmt-&gt;execute()) {
              $message = 'Successfully created new user: ' . $_POST['username'];
          } else {
              $message = 'There was an error lol';
          }
      }
  }
  ?&gt;
  </code></pre>