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, a fully functional development environment (see WAMP Server Setup Guide) and basic understanding of SQL query.


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 ‘administrator’, password ‘somepassword’, type ‘admin’
  • The equivelent SQL command would be
    INSERT INTO `myapp`.`users` (`id`, `name`, `username`, `password`, `type`) VALUES (‘1’, ‘Mr. Tom Jones’, ‘admin’, MD5(‘somepassword’), ‘admin’);
  • 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:\wamp\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");
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD); 
    if (!$connection) {
        die("Database connection failed: " . mysql_error());
    }

    $db_select = mysql_select_db(DB_NAME,$connection);
    if (!$db_select) {
        die("Database selection failed: " . mysql_error());
    }
?>
  • Create a new file called ‘close_db.php‘ in the ‘includes‘ directory and save the following code:
<?php
    mysql_close($connection);
?>
  • 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");
        $success = mysql_query($query);
            if (!$success) {
                die("Database query failed: " . mysql_error());
            }
        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 (mysql_num_rows($result) == 1) {
            // user is authenticated
            $user = mysql_fetch_array($result);
            $_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>Login Test!</title>
</head>
<body>
<?php if (!logged_in()){ 
    // render login screen
    if (isset($_GET['message'])) echo $_GET['message'];
?>
    <div align="center">
        <h1>Welcome to MyApp</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="usename" 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 an <?php echo $_SESSION['type']; ?> | [<a href="?logout=yes">logout</a>]<br />

    <!--here you can place you application content, menu etc... -->
<?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.

You can download the files for this article here.

– Girendra Persaud (November 2012)

[nrelate-related]

5 Responses to Getting Started with PHP/MySQL Programming
  1. Hi, just wanted to tell you, I liked this article.
    It was helpful. Keep on posting!

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

  3. very helpfull article, thanks.


[top]

Leave a Reply

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