Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Checking if user exists with PDO [duplicate]

Tags:

php

mysql

pdo

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.

like image 211
John Avatar asked Apr 10 '26 19:04

John


1 Answers

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.

like image 175
Atmocreations Avatar answered Apr 12 '26 09:04

Atmocreations



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!