title: Check username exists using PHP and PDO?
body: <p>I have a db.php file that has the following in it:</p>
  
  <pre><code>// db.php file
  // creates connection to database
  
  // DATABASE CONNECTION FUNCTION
  function sql_con(){
      try{
          $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS,
              array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8"));
  
          $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  
      } catch (PDOException $e) {
          // log error to file and display friendly error to user
          ExceptionErrorHandler($e);
          exit;
      }
  }
  </code></pre>
  
  <p>I have a signup page and i want to check if username already exists, so i call my <code>sql_con();</code> function beforehand to connect to database then do the below query </p>
  
  <pre><code>    // connect to database
      sql_con();
  
      $stmt = $dbh-&gt;prepare("SELECT `user_login` FROM `users` WHERE `user_login` = ? LIMIT 1");
      $stmt-&gt;execute(array($username));
  
      if ( $stmt-&gt;rowCount() &gt; 0 ) {
          $error[] = 'Username already taken';
      }
  </code></pre>
  
  <p>I'm very new to PDO and with the above i get the following errors:</p>
  
  <blockquote>
    <p>Notice: Undefined variable: dbh in C:\wamp\www\signup.php on line 64</p>
    
    <p>Fatal error: Call to a member function prepare() on a non-object in
    C:\wamp\www\signup.php on line 64</p>
  </blockquote>
  
  <p>Probably something very silly and I seem to confuse myself with PDO as I'm at the beginner stages. Could anyone tell me what I am doing wrong? Also I am not sure if this is the correct way as I'm new to PDO so if there's a more efficient way to do the username query check then please let me know.</p>