title: php check if a username exists in a database
body: <p>So I have a user <code>form</code> registration, and what I am trying to do is: while a user is typing an email, the website will check my database if the email already has been used or not, before they hit the register button. </p>
  
  <p>The problem I'm having is that it won't check. It will only display <em>"Searching in database"</em>. I just want to post my code so maybe someone can catch the error I'm making. </p>
  
  <p>This is part of my registration page:</p>
  
  <pre><code>&lt;tr class = "spacearound"&gt; &lt;!-- input for email address --&gt;
      &lt;th&gt; &amp;emsp;Email: &lt;/th&gt;
      &lt;td&gt;
          &lt;input type = "text" id = "user_email" size = "50"
              maxlength = "50" name = "u_email" 
              title = "Enter your email please" 
              onchange = "EmailCheck();" 
              onkeypress = "return InputLimiter(event, 'emailCharacters');"
              /&gt; &amp;#42;
          &lt;span id = "email_status"&gt; &lt;/span&gt;
      &lt;/td&gt;
      &lt;td&gt;&lt;?php  echo $message; ?&gt;&lt;/td&gt;
  &lt;/tr&gt;
  </code></pre>
  
  <p>This is my <strong>JavaScript</strong> file, "checkusers.js":</p>
  
  <pre><code>$('#user_email').keyup(function() {
      var username = $(this).val();
  
      $('#email_status').text('Searching database.');
  
      if(username != ''){
          $.post('checkemail.php',{ username: username }, function(data) {
              $('#email_status').text(data);
          });
      } else {
          $('#email_status').text('');
      }
  
  });
  </code></pre>
  
  <p>And this is my <strong>php</strong> file, where I check for an email, "checkemail.php":</p>
  
  <pre><code>&lt;?php
      define('dbHost', 'xxxxx');
      define('dbUser', 'xxxxx');
      define('dbPassword', 'xxxxx');
      define('dbName', 'xxxxx');
      error_reporting(E_ALL ^ E_NOTICE);
  
      $db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
  
      if(mysqli_connect_errno()) { //if connection database fails
          echo("Connection not established ");
      }  //by now we have connection to the database
  
      if(isset($_POST))['username'])){ //if we get the name succesfully
      $username = mysqli_real_escape_string($db, $_POST['username']);
          if (!empty($username)) {
              $username_query = mysqli_query($db, "SELECT COUNT(`firstName`) FROM `users` WHERE `email`='$username'");    
  
          $username_result = mysqli_fetch_row($username_query);
  
              if ($username_result[0] == '0') {
                  echo 'Email available!';
              } else {
                  echo 'Sorry, the email '.$username.' is taken.';
              }
          }
      }
  
  ?&gt;
  </code></pre>