June 21st, 2006

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 Responses to ' A Simple Login System with PHP & MySQL '

Subscribe to comments with RSS or TrackBack to ' A Simple Login System with PHP & MySQL '.

  1. dkt1133 said,

    on October 28th, 2008 at 5:38 am

    // 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. ashan said,

    on February 3rd, 2009 at 6:51 pm

    $row=mysql_fetch_array($rs);

Leave a reply

*
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.
Click to hear an audio file of the anti-spam word