PHP Programming

In this tutorial, I will show you how to quickly prepare a login screen to your PHP/MySQL web-application.  You will be introduced to Sessions, PHP functions, SQL query, MD5 encryption and PHPMyAdmin.

Prerequisites: Some basic knowledge of the C programming language or the PHP scripting language, a fully functional development environment (see WAMP Server Setup Guide) and basic understanding of SQL.


Step 1. Setting up the database with PHPMyAdmin.

The first task is to setup the database, the users table and the user records.

  • Open your favorite browser (Firefox recommended) and go to http://localhost/phpmyadmin
  • Click on the tab ‘Databases ‘ and type ‘myapp‘ where it says ‘Create new database’ and click ‘Create
  • Select the new database that you have created and create the table  ‘users‘ with 5 fields and hit ‘Go
  • on the ‘Create Table‘ screen, fill in the fields and click on ‘Save
    •     id INT( 3) PRIMARY AUTO INCREMENT
    •     name VARCHAR(100)
    •     username VARCHAR(20)
    •     password VARCHAR(60)
    •     type VARCHAR(20)
  • In the navigation area (left), click on the table ‘users‘ and click on ‘Insert‘ on the control pane (right)
  • Fill values for the fields (without the quotes) and click on ‘Go
    id ‘1’, name ‘Mr. Tom Jones’,  username ‘admin’, password ‘somepassword’, type ‘administrator’
  • The equivelent SQL command would be
    INSERT INTO `myapp`.`users` (`id`, `name`, `username`, `password`, `type`) VALUES (‘1’, ‘Mr. Tom Jones’, ‘admin’, MD5(‘somepassword’), ‘administrator’);
  • To quickly add another user you can run the query
    INSERT INTO `myapp`.`users` (`id`, `name`, `username`, `password`, `type`) VALUES (‘2’, ‘Ms. Tessa Hinds’, ‘tessa’, MD5(‘someotherpassword’), ‘officer’);
  • Now click on the table ‘users’ and it should look like the following image.
Step 2. Setting up the project directory structure.
  • Navigate to your WAMP install directory c:\wamp64\www
    Tip: you can get this quickly by going to the WAMP tray icon and click on the ‘www directory
  • Create a directory  ‘myapp
  • Inside of the directory ‘myapp‘, create the folders: ‘scripts‘, ‘includes‘ and ‘css
  Step 3. Creating the core application files.
  • Open your favorite code editor (maybe NotePadd++), create a file called ‘constants.php‘  and insert the following code and save in the directory ‘includes‘:
<?php
// Database Constants - should match those on your development machine
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "yourmysqlpassword");
define("DB_NAME", "myapp"); 
?>
  • Create a new file called ‘get_sel_db.php‘ in the ‘includes‘ directory and save the following code:
<?php
require("constants.php");

try{
 $db = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME , DB_USER, DB_PASSWORD);
}
catch(PDOException $e){
 echo $e->getMessage();
}
?>
  • Create a new file called ‘close_db.php‘ in the ‘includes‘ directory and save the following code:
<?php
 //destroying the object.... 
 $db = null
?>
  • Create a file called ‘functions.php‘ in the ‘includes‘ directory and save with the following code:
<?php
 function query($query) {
 require_once("get_sel_db.php");
 $st = $db->query($query);
 $success = $st->fetchAll(PDO::FETCH_ASSOC);

require_once("close_db.php");
 return $success;
 }
?>
  • Create a file called ‘session.php‘ in the ‘includes‘ directory and save with the code:
<?php
    session_start();
    function logged_in() {
        return isset($_SESSION['logged_in_user_id']);
    }
?>
 Step 4. Creating & Testing the Login Screen
  • Create a file called ‘index.php‘ in the ‘myapp‘ (application root directory) and save it with the following code:
<?php
 //setting up the needed includes files
 require_once("includes/session.php");
 require_once("includes/functions.php");
?>
<?php
 if (isset($_GET['logout'])) {
 session_destroy();
 $message = "You have logged out of the system. Hope to see you again.";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=?message={$message}\">";
 } else {
?>
<?php
 if (isset($_GET['login'])) {
 // process the login request
 if (isset($_POST['username'])) $username = $_POST['username'];
 if (isset($_POST['password'])) $password = MD5($_POST['password']);

$result = query("SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}' LIMIT 1");

if (!empty($result)) {
 // user is authenticated
 $user = $result[0];
 $_SESSION['logged_in_user_id'] = $user['id'];
 $_SESSION['name'] = $user['name'];
 $_SESSION['type'] = $user['type'];

// bounce to the index file with message
 $message = "You have successfully logged in!";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=?message={$message}\">";
 } else {
 // bounce to the index file with a message
 $message = "Please check your username and password and try again";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=?message={$message}\">";
 }
 }
 else {
 //render the document
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My App</title>
 <link rel="stylesheet" href="/css/styles.css" />
</head>
<body>
<?php if (!logged_in()){
 // render login screen
 if (isset($_GET['message'])) echo $_GET['message'];
?>
 <div align="center">
 <h1>Welcome to My App</h1>
 <p>To proceed, please login.</p>
 <form action="?login=yes" method="post" enctype="multipart/form-data" name="login" target="_self">
 <label>Username: </label><input name="username" id="username" type="text" />
 <label>Password: </label><input name="password" id="password" type="password" />
 <input name="submit" type="submit" value="Login" />
 </form>
 </div>

<?php
} // end if not logged in
 else {
 /// show the user that they have logged in and now can use the app
 if (isset($_GET['message'])) echo $_GET['message'];
 ?>
 Welcome <?php echo $_SESSION['name']; ?> You have logged in as <?php echo $_SESSION['type']; ?> | [<a href="?logout=yes">logout</a>]<br />

<!--here you can place you application content, menu etc... -->
 <hr/>
 <h1>Select you access level from the following:</h1>
 <div>
 [<a href="#">Do Something</a>]
 </div>
 <div>
 [<a href="#">Do Something Else</a>]
 </div>
 <div>
 [<a href="#">Do Something Else</a>]
 </div>
<?php
 } // end if successfully logged in...
?>

</body>
</html>
<?php
 } // end if not processing a login request
} // end if not loggin out
?>

Your application setup is now complete, open your favorite browser (Firefox) and go to http://localhost/myapp to test your application. You can test the login as ‘admin’ and as ‘tessa’.

Hope you enjoyed this article. Please do give us your feed-back.

– Girendra Persaud (November 2012, Update August 2017)

[nrelate-related]

5 Responses to Getting Started with PHP/MySQL Programming
  1. Hi,

    Recently I came across some great articles on your site.
    The other day, I was discussing (https://gxmediagy.com/getting-started-with-phpmysql-programming/)with my colleagues and they suggested I submit an article of my own. Your site is just perfect for what I have written!
    Would it be ok to submit the article? It is free of charge, of course!

    Let me know what you think
    Contact me at [email protected]

    Regards
    Anelie Ivanova

  2. Hi, just wanted to tell you, I liked this article.
    It was helpful. Keep on posting!

  3. I am really grateful to the owner of this website who has shared this great paragraph at at this place.

  4. very helpfull article, thanks.


[top]

Leave a Reply

Your email address will not be published. Required fields are marked *