I'm new in PHP. I try to make secure method that checks if username or email is not taken and I'm not sure if this is the right way. So my question is how can I do this better, or how would do it skilled programmer? Thanks a lot
private function checkAvailability() {
try {
$conn = new PDO(DB_SERVER, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = ("SELECT COUNT(*) FROM users WHERE username = :username OR email = :email");
$st = $conn->prepare($sql);
$st->bindValue(":username", $_POST["username"], PDO::PARAM_STR);
$st->bindValue(":email", $_POST["email"], PDO::PARAM_STR);
$st->execute();
if($st->fetchColumn() > 0) {
$sql = ("SELECT COUNT(*) FROM users WHERE username = :username");
$st = $conn->prepare($sql);
$st->bindValue(":username", $_POST["username"], PDO::PARAM_STR);
$st->execute();
if($st->fetchColumn() > 0) {
throw new Exception("That username is already taken");
} else {
throw new Exception("That e-mail is already registered.")
}
return 0;
} else {
return 1;
}
$conn = null;
} catch (PDOException $e) {
echo "Database error: " . $e->geMessage();
} catch (Exception $e) {
echo "Registration failed: " . $e->geMessage();
}
}
public function registerUser() {
if(self::checkAvailability) {
// register user
}
}