Developing Dynamic Website with PHP&MySQL - 4 - Registration and Login
29 January 2008This system is a must have for a website nowadays. Without it, you do not have a way to attract people back to your site.
The logic is very simple: you create a database table to store user registration data such as username, password, urserid, email as well as other information as required.
Database table SQL for member:
CREATE TABLE `member` (
`userid` int(10) NOT NULL auto_increment,
`email` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Run this code in phpMyAdmin, you will get a table to store user information. When users are presented with the login box, they type in the username and password, php code will compare the input values with the stored one, if all are matched, then a cookie or session will be created for the member and they become logged in.
The simple php process to log in is following:
1. create a page called: “login_form.php”. It will present
<?php
<form action=’login_process.php’ method=’post’>
<input type=’text’ name=’username’ />
<input type=’text’ name=’password’ />
<input type=’submit’ value=’Log in’ />
</form>
?>
2. create another page called: “login_process.php. It will accept values from the first page and process them.
<?php
$_session_satrt();
if($_POST[’username’] && $_POST[’password’]){
//############################
//here you will create a database connection for making sql query
//############################
$mysql_server=”database_server_url”;
$user_name = “username”;
$password = “password”;
$database=”database_name”;
$db = mysql_connect(”$mysql_server”,”$user_name”,”$password”);
@mysql_select_db($database, $db) or die(”<i>Unable to connect to database</i>”);
//to make database query to see if the two values are match
$sql = “SELECT * FROM member WHERE username=’$_POST[username]‘ AND password=’$_POST[password]‘ “;
$result = mysql_query($sql) or die(mysql_error());
//to count the number of returned records, usually one
$count = mysql_num_rows($result);
if($count > 0){
//login here
//for example, create a session value here
$_SESSION[’user’] = $_POST[’username’];
} else{
//present error message here or redirect the user back to the previous page
}
}
?>
- Next post I will introduce how to upload images as well as other types of files in PHP
No comments yet
