How to store user IDs and passwords to the mysql database
Create table tbl_auth_user (
- User_id VARCHAR (10) not null,
- User_password CHAR (32) not null,
Primary key (user_id)
- );
Insert into tbl_auth_user (user_id, user_password) VALUES ('theadmin', PASSWORD ('chumbawamba '));
- Insert into tbl_auth_user (user_id, user_password) VALUES ('webmaster', PASSWORD ('webmistress '));
We will use the same html code to create the login form created in the above example. We only need to modify the logon process. Logon script:
// We must never forget to start the session
- Session_start ();
$ ErrorMessage = '';
- If (isset ($ _ POST ['txtuserid']) & isset ($ _ POST ['txtpassword']) {
- Include 'Library/config. php ';
- Include 'Library/opendb. php ';
$ UserId = $ _ POST ['txtuserid'];
- $ Password = $ _ POST ['txtpassword'];
// Check that the user ID and password combination exist in the database
- $ SQL = "SELECT user_id
- FROM tbl_auth_user
- WHERE user_id = '$ userid'
- AND user_password = PASSWORD ('$ password ')";
$ Result = mysql_query ($ SQL)
- Or die ('query failed. '. mysql_error ());
If (mysql_num_rows ($ result) = 1 ){
- // Sessionthe set user ID and password match,
- // Set the session
- $ _ SESSION ['DB _ is_logged_in '] = true;
// Go to the homepage after logging on
- Header ('Location: main. php ');
- Exit;
- } Else {
- $ ErrorMessage = 'Sorry, wrong user id/password ';
- }
Include 'Library/closedb. php ';
- }
- ?>
//... The same html login form is the same as the previous example. Instead of checking the hard-coded information of the user ID and password, we will query the database. if the two exist in the database, we will use the SELECT query. If we find a match, we set the session variables and move them to the home page. Note that the session name is prefixed with "db" so that it is different from the previous example. In the next two scripts (main. Php and logout. Php) the code is similar to the previous one. The only difference is the session name. This is for the two codes
Session_start ();
// Is it a login to access this page?
- If (! Isset ($ _ SESSION ['DB _ is_logged_in '])
- | $ _ SESSION ['DB _ is_logged_in ']! = True ){
// No logon. return to the logon page.
- Header ('Location: login. php ');
- Exit;
- }
?>
//... Some html code here
Session_start ();
// If the user has logged on, set the session
- If (isset ($ _ SESSION ['DB _ is_logged_in ']) {
- Unset ($ _ SESSION ['DB _ is_logged_in ']);
- }
// Now, the user logs on,
- // Go to the logon page
- Header ('Location: login. php ');
- ?>
|