I have been making a login/register system and I am drawing close to finishing my register portion of code. The only problem I am running into is how to make it so that users cannot register with duplicated usernames. I want it to work so that my database wont accept the information, and it will tell the user about the error. Any help is appreciated.
My PHP
<?php
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['name'])) {//if no name has been supplied
$error[] = 'Please Enter a name ';//add to array "error"
} else {
$name = $_POST['name'];//else assign it a variable
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
//regular expression for email validation
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
I used a PDO and class method, may be of some use.
note the prepared statements too - definitely the way forward
you can do like this :
Hope that helps.
You can do it like this when the user post the username for example and click submit you can write this code or add it to your code with your modification :
You have to (can) make condition that forbids registration if username already exists.
There are two things you should do.
Make the user name a primary key in the database table. This is easily done using phpmyadmin.
Validate prior to insert.
For the second step, here's an algorithm. You may implement it in your own way using pdo, mysqli or even mysql (although it's not recommended now).
Algorithm at the end of your code (i.e., if there aren't errors)...
Hope that helps.
I think something like this is what you're looking for: