Search code examples
phplogin-script

login access able by level 1 and 2 users php


please i want to make my login page to grant users access from level 1 and 2 here is the code .

i don't know the next step from here

$query = "SELECT * FROM affiliateuser WHERE (username = '" .  mysqli_real_escape_string($con,$_POST['username']) . "') AND (password = '" .    mysqli_real_escape_string($con,$_POST['password']) . "') AND (active = '" . mysqli_real_escape_string($con,"1") . "')";
if ($result = $mysqli->query($query)) {
if ($row = $result->fetch_assoc()) {
    if($row['level'] == 1 || $row['level'] == 2) {
        // Set username session variable
    session_start();
    $_SESSION['username'] = $username;

    $errormsg= "
<div class='alert alert-warning' style='opacity: 0.5; background-color: rgb(51, 204, 102);'>   <button type='button' class='close' data-dismiss='alert' aria-label='Close'>     <span aria-hidden='true'>&times;</span>   </button>   <strong>SUCCESS...</strong> Redirecting you to dashboard. </div>";

    echo "<meta http-equiv='refresh' content='=2;dashboard' />";
    }
     else {
        //UNAUTHORIZED

please how can i make this work?


Solution

  • Problem is in your actual code, you're only selecting users with level = 1.

    The easiest solution would be to update your query to select the users where

    level IN (1,2)
    

    Another solution would be removing your WHERE level = ... clause and check that later in your PHP code. This way you could handle WRONG PASSWORD and UNAUTHORIZED errors differently

    $query = "SELECT * FROM affiliateuser WHERE (username = '" .  mysqli_real_escape_string($con,$_POST['username']) . "') AND (password = '" .    mysqli_real_escape_string($con,$_POST['password']) . "') AND (active = '" . mysqli_real_escape_string($con,"1") . "')";
    if ($result = $mysqli->query($query)) {
        if ($row = $result->fetch_assoc()) {
            if($row['level'] == 1 || $row['level'] == 2) {
                //ALL GOOD
            } else {
                //UNAUTHORIZED
            }
        } else {
            //WRONG USERNAME/PASSWORD
        }
        $result->close();
    }
    

    Note: there's no need to mysql_real_escape_string a hardcoded string when you're sure of its content: in your example 'level' will always be '1'