The method in php to store the user ID and password to the mysql database

  • 2020-05-30 19:41:54
  • OfStack

Create a user information table:

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 example above. We just need to modify the login process a little bit.
Login script:

//  We must never forget to start the session 
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
   include 'library/config.php';
   include 'library/opendb.php';
   $userId = $_POST['txtUserId'];
   $password = $_POST['txtPassword'];
   //  Check the user id And password combinations 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 Match the password ,
      //  Setting the session 
      $_SESSION['db_is_logged_in'] = true;
      //  After logging in we go to the home page 
      header('Location: main.php');
   } else {
      $errorMessage = 'Sorry, wrong user id / password';
   include 'library/closedb.php';

/ /... The same html login form before 1 example 1 like

Instead of checking the user id and password against the hard-coded information we query the database if these two exist in the database using SELECT queries. If we find 1 match we set the session variable and move to the home page. Note that the name of the session is prefixed "db" to make it different from the previous example.

In the next two scripts (main. php and logout. The php) code is similar to the previous one. The only difference with 1 is the session name. This is the code for both of them

// is 1 To log on to this page ?
if (!isset($_SESSION['db_is_logged_in']) 
   || $_SESSION['db_is_logged_in'] !== true) {
   //  Not logged in , Return to the login page 
   header('Location: login.php');

/ /... Here's some html code

//  If the user is logged in , Setting the session 
if (isset($_SESSION['db_is_logged_in'])) {
//  now , The user login ,
//  Go to the login page 
header('Location: login.php');

Related articles: