PHP Code, SQL Code

A Simple Login System with PHP & MySQL

Essential to any membership-based site is a long system. This code will provide you with the basis from which to start.

In MySQL, create a [users] table with 3 columns: login, password, last_logged_in. The last_logged_in column will store the time that the user last logged into the system.



// normally you'll get the username/pass from the $_POST variables from a form
// but for this code we'll manually create them

$username = "jim";
$password = "bob";

$sql="SELECT * FROM users WHERE login = '".$username."' AND password = '".$password."'";

// Execute the SQL statement 
// results stored in the $rs variable.

$rs = mysql_query($sql);


// determine of the mysql_query() was successful

if(!$rs) {
    $err=mysql_error();
    print $err;
    exit();
}

// If was successful, check returned result
// mysql_affected_rows() will return the number of rows affected

if(mysql_affected_rows()==0){
     print "Username/password pair is invalid. Please try again.";
} else {
     // display last logged in time
     $row=mysql_fetch_array($r);
     $last=$row["last_logged_in"];
     print "Login successful. (You last logged in at ".$last.".)";
}

Of course, in real-world applications you won't want to store the password in plain text, but encrypt them with the PASSWORD function or a custom encryption method.

Share

2 Comments

  1. // normally you'll get the username/pass from the $_POST variables from a form
    // but for this code we'll manually create them

    $username = "jim";
    $password = "bob";

    $sql="SELECT * FROM users WHERE login = '".$username."' AND password = '".$password."'";

    // Execute the SQL statement
    // results stored in the $rs variable.

    $rs = mysql_query($sql);

    // determine of the mysql_query() was successful

    if(!$rs) {
    $err=mysql_error();
    print $err;
    exit();
    }

    // If was successful, check returned result
    // mysql_affected_rows() will return the number of rows affected

    if(mysql_affected_rows()==0){
    print "Username/password pair is invalid. Please try again.";
    } else {
    // display last logged in time
    $row=mysql_fetch_array($r);
    $last=$row["last_logged_in"];
    print "Login successful. (You last logged in at ".$last.".)";
    }

  2. $row=mysql_fetch_array($rs);

Leave a Reply

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image