For some reason with the code I have now, It’s still letting me insert the same username over and over again. How I can properly prevent that from happening?
function register(){
if (isset($_POST['username'], $_POST['password'])) {
$query = dbConnect()->prepare("SELECT COUNT(*) FROM users WHERE username= :username ");
$query->bindValue(':username', $_POST['username']);
$row = $query->fetchColumn(PDO::FETCH_NUM);
if($row > 0){
die('ERROR: This username is already taken!');
}
}
}
You would need to set a unique index constraint on the username column in the database (if it can’t be the or part of the primary key). That would prevent duplicates from being inserted and also throw a duplicate insertion error.
That’s something you would handle within PHP. You’re basically on the right track with your PHP code, although I wouldn’t use die() to communicate with the user. I would return to the form they submitted and include the message that the username was in use so that they could pick a different one and try again.
Some pseudo-code:
$query="SELECT username";
if($row=$query->fetch()){
echo "sorry, that name is taken. Pick something else";
//TODO: present the the submission form with the user-entered information, minus the username
}
else{
echo "The name is available".
//TODO: either say it's available or go ahead and register the user.
}
Without knowing what the rest of your code looks like, I can’t really offer any specific code suggestions.