icenine icenine - 2 months ago 7
PHP Question

Booleans SQL and PHP validation

I have a column in a table (users) called admin and its datatype is boolean. Two users are set to "true"

My objective is when those two log in, they have acess to the back office, but so far the code isn't working:

<?php

session_start();

$error="";
$successMessage="";



if ($_POST){
if(!isset($_POST["salada"]) || $_POST["salada"]===""){
$error = "PHP: An email is required <br>";
}



if(!isset($_POST["arroz"]) || $_POST["arroz"]===""){
$error .= "PHP: A password is required";
}

if ($error !=""){
$error = '<div class="error-login">'.$error.'</div>';


}else {

require("MGconfig.php");


$email = mysqli_real_escape_string($connection, $_POST["salada"]);
$pwd = md5(mysqli_real_escape_string($connection, $_POST["arroz"]));


$result = mysqli_query($connection, "select name, id from users where email = '".$email."' and password = '".$pwd."'");


if (mysqli_num_rows($result) !==1){
$error='<div class="error-login">PHP: Invalid email or password</div>';
header("Location:index.php?error=".$error);

}else {

$nome = mysqli_fetch_row($result);

$_SESSION["name"] = $nome[0];
$_SESSION["id"]=$nome[1];



header ("Location: main.php");
}
}


}

?>

<?php

if($_SESSION['admin'] !=0){

header ("Location:admin.php");
}?>


Can someone tell me why isnt working? Is Syntax? If I compara the field "name", the restriction works...Thanks in advance!

Answer

The problem is, you haven't selected admin column in the SELECT query, you have only selected id and name columns. Plus, there's nowhere you're checking whether the logged in user is admin or not.

So the solution is, select the admin column in your SELECT query and make use of that column value to check whether the logged in user is admin or not, like this:

// your code

$result = mysqli_query($connection, "select name, id, admin from users where email = '".$email."' and password = '".$pwd."'");

if (mysqli_num_rows($result) !== 1){
    $error='<div class="error-login">PHP: Invalid email or   password</div>';
    header("Location:index.php?error=".$error);
}else{
    $nome = mysqli_fetch_row($result);
    $_SESSION["name"] = $nome[0];
    $_SESSION["id"] = $nome[1];
    if($nome[2]){
        // logged in user is admin
        $_SESSION["admin"] = true;
    }else{
        // logged in user is not admin
        $_SESSION["admin"] = false;
    }
    header ("Location: main.php");
    exit();
}

// your code

Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.