Today i will be guiding you through on how to make a PHP registration system for your website. You will need PHP version 5+ and mysql 5+ running and fully setup. If you haven’t got these running and a webserver system, please download acopy of xampp for your system: xampp. In this tutorial you will learn firstly how to structure your database to accept typical user information, connect to a mysql database and select the appropriate database, deal with HTML forms and user input, error check user input, and finally insert records into a database.
Firstly, and thanks to people who have commented, it has been brought to my attention my code is not secure. Please review this site: here as you go along! Next tutorial i will go about including these issues. Feel free to go through the entire tute my way, then learn these security measures, i think this is a good way to learn!
By the time we are finished, this is what it will look like + it will work:

1. Structuring your database with phpMyAdmin
So firstly load up phpmyadmin, if this is your first look at phpMyAdmin please read up on it a bit first, this tutorial really isn’t a look at the tools, but merely how to make what we want to make. Anyway, create a new database called ‘regtut’.

Next lets make our users table. This is where all the information on your users will be stored when they are allowed to register. So make a table called users. With the number of fields as 5. We will use these fields: id, username, password, email, datejoined in our database. So firstly type all these names in the field column with the data types of, int(6), varchar(63), varchar(63), varchar(31), varchar(127), timestamp, respectively. So your entries should look like:

Before we go ahead, we need to edit the id column. Make sure it is the primary key, and has an extra detail of autoincrement. By doing both of this you will firstly, make mysql associate the id column as a primary key, inturn will index the column, dedicating more system resources to the column which will result in faster queries on the column, and secondly, adding the autoincrement will +1 onto the current row number when a new record is inserted. For example. You start off on the first row, it gets an id of 1, you insert the next row its id is 2. However when you delete a row, the id number value wont decrease, but stay on the same row value.
So thats it for the database part, click save. Make sure you know your username and password, which you would of had to know inorder to get into phpMyAdmin. Now onto the php part.
2. Connect to the database
So now we are up to the PHP part of the tutorial, and this is what we are all after i guess. Make a new file on your webserver, called register.php. It will be a blank file, make sure you know where you put it on your webserver and going to the address. i.e. “http://www.godsdomain.com/register.php”. Next open the file in dreamweaver, or notepad, or whatever you use to see the text. Now we begin.
Lets add the php tags. type in:
<?php
?>
This declaration says whatever between these two tags is php code, so apache or whatever, should pass off any calculations and processing of the code in between to the php processor. Now what we want to do, is connect to the database, with our username and password used to connect to the mysql database. Inbetween these two tags, type in, but replace the values with what you use:
$config['address'] = ‘localhost’;
$config['username'] = ‘reguser’;
$config['password'] = ‘nightgen’;
$config['databasename'] = ‘regtut’;
What this does, is, simply store text into an array, variables. Variables always begin with a $ sign, and in php, can hold any data type, php is dynamic in setting the data types stored, which is nice. This code does nothing at all functionally, but we are getting to that now. Now we will add the database connections used by php. Below this code above type in:
mysql_connect($config['address'], $config['username'], $config['password']);
mysql_select_db($config['databasename']);
If something went wrong, such as a bad username or password you supplied, php will show errors on the page. If you just see a blank page, congratulations, everything worked just fine, and you have connected to your database. Next, the HTML part.
3. Building the form
Now we have arrived to building the html to our site. It is a basic userinput form. Type in the following, under the ?> tag, and i will explain below:
<form name=”reg” method=”post” enctype=”application/x-www-form-urlencoded”>
username: <input type=”text” name=”username” /><br />
email: <input type=”text” name=”email” /><br />
password1: <input type=”password” name=”password1″ /><br/>
password2: <input type=”password” name=”password2″ /><br/>
<input type=”submit” name=”submit” value=”register” />
</form>
Of course your database connections should look different. Anyway, an explanation of what the HTML does. Firstly the form tag. This tells the browser, anything between the <form> and </form> tags, is one user input area. So any submit button in there, will only submit the fields inside the form tags. Which means you can have multiple forms on a page, and only submit a select number of user input fields on a page. The method variable in the <form> tag states that we should use the POST method to transfer the data to the server, which is passed through with a transaction, instead of GET which users requests via the address bar. Don’t worry too much about that or the enctype.
Next we have the username field, which allows text inserted into it (the type) and has a label called username, which we use to receive and handle the in putted data later. The same is with email. Password 1 and 2 have the input type of password, which means it just shows stars to conceal the data entered on the screen. Both have different names, which again will help us later. Lastly comes the submit button, which will send all the data in the form, to the server, which is our next part.
4. Handling user inputs
We now have a nice form, and a database connection, next we have to handle this user input to make sure all data was entered correctly, and fits to how we want it. But first, lets make sure our form is working ok, and to show you how we will be handling the data. Back above the ?> tag now, insert this:
echo $_POST['username'];
Now go to the page in your browser, fill in the username field and click submit. You will now see the form again, and whatever you typed in the username field. We access any information sent to the server, via the $_POST array. See how our labels come into effect now? Anything we named in the form and input fields, is now accessed via the $_POST array. For example, email; $_POST['email'] and password1 $_POST['password1']. Try it out. Now we will make sure the user has imputed correct data. Firstly test to see if the form has been submitted, we do this by checking if the submit button has been clicked, or, if it has a $_POST value. So replace the echo statement we just used with:
if($_POST['submit']){
}
Excellent. So what this says, is, if $_POST['submit'] has a value, then do whatever is inside these shiny new brackets. Now lets do something within these shiny new brackets. Lets test if the username is firstly entered, if so it is at least 3 characters long, and that the username does not exist yet in the database. Type in the following, between the curly brackets we just made:
$_POST['username'] = trim($_POST['username']);
if($_POST['username'] && strlen($_POST['username']) >= 3){
$query = mysql_query(”SELECT `id` FROM `users` WHERE `username`=’”.$_POST['username'].”‘ LIMIT 1″);
if(mysql_num_rows($query)){
$error['userexists'] = ‘Username exists’;
}
} else {
$error['usernameinput'] = ‘Please enter a username of 3+ characters’;
}
Looks a hell of a lot more confusing right? Let me walk you through it, because the others i will not be explaining, as it just follows the same theory.
First Line: Get rid of any spaces before or after the user text input.
Second Line: If the username field has something in it, and the text entered has or has more than 3 characters then proceed.
Third Line: So the username was entered and it was long enough. Now search the database for the username that was entered. We use LIMIT 1 so it stops querying the database once a record is found, which is all we need to make an error.
Fourth Line: Tests to see if the query we made on the users table, found a username which matches the username the user inputted.
Fifth Line: Add to the $error array, with the identifier of ‘userexists’, the error text.
Eight Line: If the username was too small, or nothing was entered, add to the $error array with a request to enter a username.
Now we will test our user error checker works. Put this code next to user input field:
<?php echo $error['userexists']; echo $error['usernameinput']; ?>
Your code should now look like:
Great, you checked to make sure the user input went well. Now i will make the rest of the error checking, and you put it in, between those two main curly brackets, the ones that tested if the submit button was pressed:
Email Test:
$_POST['email'] = trim($_POST['email']);
if($_POST['email']){
if(!eregi(”^[a-zA-Z0-9]+[a-zA-Z0-9_.-]*@[a-zA-Z0-9]+[a-zA-Z0-9_.-])*\.[a-z]{2,4}$”, $_POST['email'])){
$error['emailerror'] = ‘Email Incorrect’;
}
} else {
$error['emailinput'] = ‘Please supply an email address’;
}
Password Test:
if($_POST['password1'] && $_POST['password2']){
if($_POST['password1'] != $_POST['password2']){
$error['passmismatch'] = ‘Passwords don\’t match’;
}
} else {
$error['passwordinput'] = ‘Please enter your password in both fields’;
}
Also add the error reports next to the form with:
<?php echo $error['emailerror']; echo $error['emailinput'];?>
<?php echo $error['passmismatch']; echo $error['passwordinput']; ?>
Yayyy so your page should now look like:
![]()
Now, all the error checking works. So what does this mean? Well we will check the $error variable now, if there are no errors, do something, otherwise keep showing the page. So just above the ?> tag, insert an if statement:
if(!$error && $_POST['submit']){
} else {
What this does, is, if the $error array is empty (checks empty with ! to see if it returned a 0) then proceed. If you didnt, have the ! sign, and if $error was empty, it would return a 0 and inturn would be false, it would then execute the else statement instead. We don’t want that, we want the form section of the site in the else statement. So add that to your page just above the ?> and we will add:
<?php
}
?>
to the very bottom of the page. So your code should now look like:
![]()
Right, so we will add something within this if statement, when there are no errors. We will now insert the user into the database! And also echo a thank you. This will conclude the tutorial also, yes, you’re at the end.
Between the curly brackets of the if (!$error && $_POST['submit']) statement, add:
$query = mysql_query(”INSERT INTO `users` (username, email, password) VALUES (’”.$_POST['username'].”‘, ‘”.$_POST['email'].”‘, ‘”.md5($_POST['password1']).”‘)”);
if($query){
echo $_POST['username'].’ is now registered’;Now let me explain. The first line inserts the records into the database with a mysql statement. Notice the md5 on the password. This encrypts the password for storage into the database, and makes sure no one can read nor decrypt user’s passwords if they got their hands on the database itself. If you are wondering, if i can’t decrypt it, what good is that. Don’t worry, you have no need to decrypt it. If you want to build a user authentication/login system, you just md5 the submitted password and see if the submitted password matches the md5′d password in the database. Confusing? don’t worry again, you don’t need to understand for this tutorial.
Next it checks if the query worked ok, i.e the user was inserted, then it says on the page, great, the user was inserted.
All worked for me! But debugging never stops, so if you find an error or a bug, let me know. Here is what i see
I hope this tutorial has helped you on your way to PHP programming! Perhaps, if i get enough requests, and nice feedback, i will extend this tutorial and show you how to make a user login system
Enjoy,
VoiDeT
Source Files:
sql.txt
register.txt
register (with email mod).txt
**Note i forgot to add a check for existing emails. But if you weren’t sleeping during this tutorial, you should port what i did in the username check to the email check
so that is an exercise for you to do.**






I love it! Just awsome
Excellent tutorial! Thank you, it was very helpful. Straight to the point and much easier to understand that most other PHP tutorials.
Ive read a few ‘getting started with mysql and php’ tutorials, but this is the best ive found! nice work.
Besides that I find this coding style rather ugly (it looks like spaghetti, which is fine but not for code), there are some quite unsafe practices in here, especially in regard to SQL and XSS leaks. Please read a few articles on PHP security and web application security in general. You can find one at http://www.daholygoat.com/blog/index.php?/archives/6-Writing-Secure-Web-Applications-with-PHP.html
Are you guys serious? This thing is poorly coded and extremely insecure. People never even having heard of SQL could inject this thing. You have $_POST’s right in the queries!
thanks!
Thanks so much, Please mkae a login system
thanks again
Excellent tutorial, i need to make a username and password registration to access to an especific page. Don´t you know something about it?.
thanks!
I can’t add your post to Digg. How I do this?
Plz Provide me more information about how to send registration form data to site e-mail address so we can check that data.
Work that out yourself. Look at the mail function. This is a tutorial site, not a free web development haven.
Hey there nice tutorial.
there is one problem, i keep on getting this $end error message!!!!
Parse error: syntax error, unexpected $end in /home/rickyb/public_html/php/register.php on line 57
Please help!!!
means you forgot to put a } somewhere Ricky
Wow it worked!!! thanks VoiDeT!
but unnfortuntly im getting enother error lol
Everything seems to go to plan when i type my info out now but when i submit the information i get this error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/rickyb/public_html/php/register.php on line 16
please help
Thanks heaps for the prompt responce VoiDeT
Ricky
This is my code:)
Ah that must be because you have no registered users yet.
change this “if(mysql_num_rows($query)){” to “if(@mysql_num_rows($query)){”
That should solve it
It worked!!!
LOL but now as iv conquered those errors it dosn’t seem to show up in the database and also i dosnt seem to echo that line saying thankyou for registering!
This is ther Url where im hosting the register.php
http://www.toxinstudios.com/php/register.php
Thanks So much agin for the prompt response!!!
Ricky
would it be something to do with the connection??
When I register the inputs don’t get added to the database
Nice work!
excellent tutorials,
very useful to me. i highly apperciat this site
chaminda
found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later ..
Can yuo please make a PHP Login System Tutorial???
THANKS!!!!
NICK
hi i have used your code great code but do i need to do something in phpMyAdmin to link the code so the name of the person shows in the database?
Today good day
The interesting name of a site - blog.nightgen.com
The interesting site but does not suffice several sections!
I yesterday 4 hours
sat in the Internet So I have found your site
However this section is very necessary!
Best wishes for you!
Forgive I is drunk :))
I cant do it, your code is full of bug
If you get a blank page returned after you submit a new entry and the details are not added to the database this could be due to a mis-print on the INSERT statment
approx line 65
$query = mysql_query(”INSERT INTO ‘users’ (username, email, password) VALUES (’”.$_POST['username'].”‘, ‘”.$_POST['email'].”‘, ‘”.md5($_POST['password1']).”‘)”);
THERE SHOULD BE NO QUOTES AROUND USERS… IT SHOULD READ
$query = mysql_query(”INSERT INTO users (username, email, password) VALUES (’”.$_POST['username'].”‘, ‘”.$_POST['email'].”‘, ‘”.md5($_POST['password1']).”‘)”);
GOOD LUCK!