Saturday, February 18, 2012

PHP simple user Registration + Login system


  •  First thing, create a MySQl database with the following structure:














  • You could create this with the Xamp's PhpMyAdmin utility, or running commands at the php console, or by running commands as a php program.
  • I've named the above database as "test", and the table as "bkmark_users".
  • Now, we need following 5 files to create the Registration + Login system:

  1. Login.html: User interface for user registration / login. Includes forms that execute the php codes in CheckLogin.php and Register.php in order to register and login users.
  2. CheckLogin.php: Search the database for the user inputted username and password to log her/him in. Also creates cookies for storing username and pass.
  3. Register.php: Writes the user inputted new username and pass into the database as a new user record.
  4. ProtectedPage.php: This is the page protected by passwords. Firstly it checks whether a user has logged in by checking the cookies. If not, opens the Login page. Also it extracts the username using the cookie to display a message.
  5. Logout.php: Closes the session deleting the cookies, indicating the user have logged out. Then redirects the user to the Login page.

Ok below are the complete file sources:

Login.html

<html>
<head>
<title>My Website - Login</title>
</head>
<body bgcolor="#FFFFCC">
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<table style="margin:15px auto;" align="center">
<tr>
<td colspan="3"><h2>Login:</h2></td>
</tr>
<tr>
<form action="CheckLogin.php" method="post">
<td>Username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" name="Submit" value="Login"/></td>
</form>
</tr>
</table>
<table style="margin:15px auto;" align="center">
<tr>
<td colspan="3"><h2>Register:</h2></td>
</tr>
<tr>
<form action="Register.php" method="post">
<td>New username:</td>
<td><input type="text" name="newusername"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="newpassword"/></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" name="Submit" value="Register"/></td>
</form>
</tr>
</table>
</html>


CheckLogin.html

<?php
session_start();
$username = $_POST["username"]; // This is the inputted username from the form in Login.html
$password = $_POST["password"]; // This is the inputted password from the form in Login.html

mysql_connect('localhost');
mysql_select_db('test') or die('Could not select database');

$result = mysql_query("SELECT username, password FROM bkmark_users"); // Get data from username and password fields

$hituser=false;
$hitpass=false;
// Sarch username in the database
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
if($row[0] == $username){ // If found, open ProtectedPage.php. Else goto Login.html
$hituser=true;
if($row[1] == $password){
$hitpass=true;
echo "USER FOUND!";
$_SESSION["username"] = $username; // Creates a cookie saving the username
$_SESSION["loggedIn"] = true; // Creates a cookie saying the user is logged in
header("Location:ProtectedPage.php");
}else {
}
}else{
// header("Location:Login.html"); // Lastly, redirect back to login page
}
}
if($hitpass==false){
echo "PASSWORD INCORRECT!<br>";
}
if($hituser==false){
echo "USER NOT FOUND!<br>";
}
?>


Register.html

<?php
session_start();
$newusername = $_POST["newusername"]; // This is the inputted username from the form in Login.html
$newpassword = $_POST["newpassword"]; // This is the inputted password from the form in Login.html

mysql_connect('localhost'); // *** INSERT YOUR DATABSE INFORMATION HERE ***
mysql_select_db('test') or die('Could not select database');

mysql_query("INSERT INTO bkmark_users(username, password) VALUES('" . mysql_real_escape_string($newusername) . "','" . mysql_real_escape_string(
$newpassword) . "')")or die('Could not insert data into db');
echo "New user created:<br>";
echo $newusername."<br>";
echo $newpassword."<br>";
echo "<a href='Logout.php'>Logout</a>";
?>


ProtectedPage.html

<?
session_start();
if(!$_SESSION['loggedIn']) // If the user IS NOT logged in (the loggedIn cookie is created), forward them back to the login page
{
header("location:Login.html");
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>My Website - Protected Content</title>
</head>
<body bgcolor="#FFFFCC">
<?php

// If the user IS logged in, then echo the page contents:
$currentUser = $_SESSION['username']; // Gets the username from the cookie we created in Check.php
$message = '<p>Welcome, ' . ucfirst($currentUser) . '!</p>'; // This compiles hello (your username)
echo $message; // This echo's (actually outputs) the message
?>
<p>Good job! You got it working!!</p>
<a href="Logout.php">Logout</a>
</body>
</html>


Logout.html

<?php
session_start();
session_destroy();
header("Location:Login.html");
?>


Create these files inside the same folder and run the Login.html file. Enjoy!

Wednesday, February 15, 2012

PHP and MySql. How to connect to a database, Create a table, and add data




Below code will,


1. Make a sql connection to localhost (display error if something goes wrong).
2. Select the database "test" as the working db.
3. Create a table named example2 inside the "test" db.
4. Set the member variables and their data types in the table.
5. Insert 3 rows of data into the table.
6. Retrieve back the data from the table as a resource ($result).
7. Use the resource to print out the contents inside the table, with a while loop.


=============================================================

// 1. Make a MySQL Connection
mysql_connect("localhost") or die(mysql_error());


// 2.
mysql_select_db("test") or die(mysql_error());


// 3. Create a MySQL table in the selected database
mysql_query("CREATE TABLE example2(
id INT NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(id),
 name VARCHAR(30), 
 age INT)")
 or die(mysql_error());


// 5. Insert rows of information into the table "example2"
mysql_query("INSERT INTO example2 
(name, age) VALUES('Timmy Mellowman', '23' ) ") 
or die(mysql_error());  


mysql_query("INSERT INTO example2 
(name, age) VALUES('Sandy Smith', '21' ) ") 
or die(mysql_error());  


mysql_query("INSERT INTO example2 
(name, age) VALUES('Bobby Wallace', '15' ) ") 
or die(mysql_error());  


// 6. Retrieve all the data from the "example2" table
$result = mysql_query("SELECT * FROM example2")
or die(mysql_error()); 
 
// 7. store the record of the "example2" table into $row
// Print out the contents of the entry 
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "
";

}


?>
=============================================================


(( SQL help ))


SQL CREATE TABLE Syntax


CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)



SQL INSERT INTO Syntax


INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

SELECT * Example


The SELECT statement is used to select data from a database.

The result is stored in a result table, called the result-set.

The asterisk (*) is a quick way of selecting all columns! 

The mysql_query() function 
Executes a query on a MySQL database. 

The mysql_fetch_array() function
Returns a row from a recordset  





My Facebook Music group

  🎧𝅘𝅥𝅲 M̾U̾S̾I̾X̾ ♭🎧