3

I'm setting up a function in order to check if a passed username exists in the users table in my database. In order to do this, I'm using the following code:

function usernameCheck($username) {
    $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $stmt = $con->prepare("SELECT username FROM users WHERE username = ':name'");
    $stmt->bindParam(':name', $username);
    $stmt->execute();

    if($stmt->rowCount() > 0){
        echo "exists!";
    } else {
        echo "non existant";
    }
}

However, no matter what I try setting as $username, I can't get any exists! back. I've tried changing it around to check for an additional column, like userID, but it still doesn't work. I think my syntax is correct, but I'm new to PDO so I'm probably missing something easy to fix.

Thank you.

John
  • 293
  • 2
  • 6
  • 18

2 Answers2

12

You don't need the escaping.

$stmt = $con->prepare("SELECT username FROM users WHERE username = :name");

Writing :name without any quotes should do the trick. The PDO-library already does the escaping for you.

Atmocreations
  • 9,923
  • 15
  • 67
  • 102
0

Try the below SQL Query

$query="SELECT username FROM users WHERE username = 'name'";
$query_res =   $con->query($query);
$count= count($query_res->fetchAll());
if($count > 0){
 //user exists
}
Venkat.R
  • 7,420
  • 5
  • 42
  • 63
Hakim
  • 17
  • 1