Check if username exists

Hi There,
I’m rather new to php so please bare with me! :wink:
After many attempts i still have been unable to return success, even existing usernames still come up as free. ???
this is the code i’ve been attempting to use;

[php]<?php
}else{

$usr = new Users;
$usr->storeFormValues( $_POST );
if( $_POST[‘password’] == $_POST[‘confpass’] ) {
//passwords do match//
} else {
echo “Passwords do not match”;
exit;
}
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare(“SELECT COUNT (*) FROM users WHERE username = :username”);
if ($stmt->fetchColumn() > 0) {
echo “username is taken”;
}else{
echo “username is free”;
}
}
?>[/php]
Thanks, I Appreciate it!

Hey I am new to this aswell … and dont know if it will work but try this?

[php]
$stmt = $con->prepare(“SELECT COUNT (*) FROM users WHERE username = :username”);

$usercheck = mysql_num_rows($stmt)
if ($usercheck != 0) {

echo “username is taken”;
}else{

echo “username is free”;
}
[/php]

The problem is the :username since it’s not defined nor replaced anywhere. First of all you need the username from the $_POST array I assume. Then you need to execute the prepared statement with
[php]$stmt->execute(array(’:username’=>$username_from_post_etc))[/php]. I’m not sure where you are going with the fetchColumn call either. Maybe just use fetchAll() which returns an array for convenience. Using COUNT(*) is also unnecessary. You can just use SELECT * FROM users WHERE username = :username…

And you cannot mix pdo and mysql-extensions like cory said.

Sweet, Thanks for the replies guys!
Finally it works!
Here is my final code;
[php]<?php
}else{

$usr = new Users;
$usr->storeFormValues( $_POST );
if( $_POST[‘password’] == $_POST[‘confpass’] ) {
//passwords do match//
} else {
echo “Passwords do not match”;
exit;
}
$username = ( $_POST[‘username’]);
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sthandler = $con->prepare(“SELECT username FROM users WHERE username = :username”);
$sthandler->execute(array(’:username’=>$username));
if ( $sthandler->rowCount() > 0 ) {
echo (‘Sorry, the username ‘.$_POST[‘username’].’ is already in use.’);
}else{
echo “username is free”;
}
}
?>[/php]

Thanks Again!

Sponsor our Newsletter | Privacy Policy | Terms of Service