hi .. i need help .. i'm making a login page with sign-up feature .. meaning if you are not already registered in the database you have to sign-up on the sign-up page .. i know how to make the pages but my only problem is ..

how can i check if the username & password already registered in the database .. (i'm talking about mysql database) ..

if i'm not mistaken i have to make IF and ELSE statements to validate the username & password right ? ..

please help me .. THANK YOU VERY MUCH ..

Dani AI

Generated

provides a clear, working login/register flow that answers the basic question from . Important context: this thread is from 2011, and some APIs and practices used back then are now insecure or deprecated. The core improvements to make the flow production-ready are: use parameterized queries (PDO or mysqli) to stop injection, use a modern password hash (password_hash / password_verify or Argon2 where available), enforce a UNIQUE constraint on the username column at the database level, and harden session handling and transport (HTTPS, regenerate session ID at login, set Secure/HttpOnly flags).

Recommended minimal workflows (no client-only validation):

  • Registration: validate and normalize inputs server-side, hash the password with password_hash(), attempt insert using a prepared statement, and handle duplicate-key errors (or pre-check with a prepared SELECT if preferred). Consider email verification before enabling the account.
  • Login: fetch the stored hash by username with a prepared statement, use password_verify() to compare, call session_regenerate_id() on success, and avoid revealing whether the username or password was incorrect. Implement login throttling / temporary lockout after repeated failures.

Small examples of modern practices (conceptual, safe to paste into codebase):

$hash = password_hash($password, PASSWORD_DEFAULT);
// store $hash in DB
// PDO: fetch row by username safely
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE username = ?');
$stmt->execute([$username]);
$row = $stmt->fetch();
if ($row && password_verify($password, $row['password_hash'])) {
    session_regenerate_id(true);
    // set session and continue
}

Cautions: never echo raw DB errors to users, always serve login pages over HTTPS, escape output with htmlspecialchars to avoid XSS, and log authentication failures for monitoring. These changes keep the basic flow from the original posts but make it safe and maintainable today.

Recommended Answers

All 2 Replies

Hello dear
How are you....?
I'm Shujaat form Pakistan
here is complete solution of your problem

save this code with page name: connect.inc.php

<?php					//To connect script with database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';

$mysql_db = 'a_database';

if(!mysql_connect($mysql_host, $mysql_user, $mysql_pass) || ! mysql_select_db($mysql_db)){
  die(mysql_error());
}  
?>

Save this page with name: core.inc.php

<?php
ob_start();     //ob_start should start before use of header function, which is to     redirect our user back to index page when they login correctly
session_start();	 //session_start should initialize before we use session

$current_file = $_SERVER['SCRIPT_NAME'];	//{'SCRIPT_NAME'} tell us what is current page
$http_referer = $_SERVER['HTTP_REFERER'];

//function to check weather session is empty or not?
function loggedin(){	
  if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
    return true;
    }else{
          return false;
          }
}

      function getUserField($field){
        $query = "SELECT $field FROM users WHERE id = '".$_SESSION['user_id']."' ";
        if($query_run = mysql_query($query)){
          if($query_result = mysql_result($query_run, 0 , $field)){
            return $query_result;
          }else{
            echo 'Love.';
          }
        }
      }
?>

save this page with name: loginform.inc.php

<?php
//this should not userequire 'core.inc.php';
require_once('core.inc.php');	

//cheching login form is empty or not? And then form data send to database server to compare weather data is valid or not? After that start session if data is valid.
if(isset($_POST['username']) && isset($_POST['password'])){
  $username=$_POST['username'];
  $password=$_POST['password'];
  $password_hash = md5($password);				//converting data to md5

  if(!empty($username) && ! empty($password)){
//here we select id form table rather username, so that we can access whole data of a user who logged in
    $query = "SELECT id FROM users WHERE username = '".mysql_real_escape_string($username)."' AND password = '".mysql_real_escape_string($password_hash)."'";
    if($query_run = mysql_query($query)){
      $query_num_rows = mysql_num_rows($query_run);
      if($query_num_rows==0){
        echo 'Invalid';
      }else if($query_num_rows ==1){
      //mysql_result have take these three arguments, 
      //$query, The result resource that is being evaluated. This result comes from a call to mysql_query().
      //Then Row(0) The row number from the result that's being retrieved. Row numbers start at 0.
      //third one is "field" The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

      $user_id = mysql_result($query_run, 0, 'id');
        echo $user_id;
        $_SESSION['user_id']=$user_id;		//starting session and assigning user id to recognize user
        header('Location: main.php');		//header return user to main.php page
      }
    }
  }else{
    echo 'You must enter a username and password.';
  }
}
?>
<form action="<?php echo $current_file; //variable recognize current page of website  ?>" method="POST">		
Usrename: <input type="text" name="username">
Password: <input type="password" name="password">
          <input type="submit" value="Log in">
</form>

save this page with name: logout.php

<?php
require 'core.inc.php';
           
session_destroy();

header('Location:'.$http_referer);
?>

save this page with name: main.php

<?php
require 'core.inc.php';			//calling other page which has some function of login part
require 'connect.inc.php';		//calling other page which has some function of login part

//loggedin function is declare in core.inc.php page to check that weather session is exist or not and session is continue or not?

if(loggedin()){
  $firstName = getUserField('firstname');
  $surName   = getUserField('surname');

  echo 'Welcome '.$firstName.' '.$surName.'...!<br> You are login. <a href = "logout.php">LogOut</a><br>';

}else{
  include 'loginform.inc.php';
}
?>

save this page with name: register.php

<?php
require 'core.inc.php';
require 'connect.inc.php';
if(!loggedin()){

  if(
     isset($_POST['username']) &&
     isset($_POST['password']) &&
     isset($_POST['password_again']) &&
     isset($_POST['firstname']) &&
     isset($_POST['surname'])
  ){

     $username       = $_POST['username'];
     $password       = $_POST['password'];
     $password_hash  = md5($password);
     $password_again = $_POST['password_again'];
     $firstname      = $_POST['firstname'];
     $surname        = $_POST['surname'];

         if(
            !empty ($username) &&
            !empty ($password) &&
            !empty ($password_again) &&
            !empty ($firstname) &&
            !empty ($surname)
         ){

              if($password == $password_again){
                $query = "SELECT username FROM users WHERE username = '$username'";
                $query_run = mysql_query($query);


                  if(mysql_num_rows($query_run)==1){
                    echo 'Sorry..! This user name '.$username.' already exist. <br>Please try with any other.';
                  }else{
                    $query = "INSERT INTO users VALUES ('', '$username', '$password_hash', '$firstname', '$surname')";
                      
                      if($query_run = mysql_query($query)){
                        header('Location: register_success.php');
                      }
                  }


              }else{
                echo 'Password is not matching.<br> Please enter again same password.';
              }

         }else{
           echo 'All fields are required. Thanks';
         }



  }

?>
<form action="register.php" method="POST">
Username:<br>   <input type ="text" name="username" value = "<?php echo $username; ?>"><br><br>
Password:<br>   <input type ="password" name="password"><br><br>
Password Again: <br> <input type="password" name="password_again"><br><br>
First Name:<br> <input type="text" name="firstname" value = "<?php echo $firstname; ?>"><br><br>
Sur Name:<br>   <input type="text" name="surname" value = "<?php echo $surname; ?>"><br><br>
                <input type="submit" value="Register" >
</form>

<?php
}else if(loggedin()){
  echo 'You\'re logged in.';
}
?>

save this page with register_success.php
You are register


now this is complete solution of your problem.
Take care
&
Best of Luck

Thank You very much Shujaat .. i really appreciate your effort on helping me .. i'm gonna review this one for awhile .. coz i don't wanna pass the exam without understanding it ..

again THX .. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.