Login panel does not return the number of accounts

Asked

Viewed 94 times

4

I am creating a login area, but when I click the login button, it does not return any error, for example: if the user does not exist I would like the number 0 to appear according to the variable $num, but a blank screen appears on the page.

PHP:

    $conn = mysqli_connect($servidor, $usuario, $senha, $dbname) or die(mysqli_error());


    if (isset($_POST['email']) && isset($_POST['senha'])) {

      $email = $_POST['email'];
      $senha = $_POST['senha'];

      $get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE email = '$email' AND senha = '$senha'");
      $num = mysqli_num_rows($get);

          echo $num;
    }
?>

HTML:

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="login.php" method="post">
            <input type="text" name="usuario" placeholder="Usuário"><br>
            <input type="password" name="senha" placeholder="Senha"><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

  • Most likely falling into condition: if (isset($_POST['email']) && isset($_POST['senha'])) {. By the way, where is the key closing this condition?!

  • I didn’t post the whole comic hehe, but it has the key closing the condition, I’m beginner, and I couldn’t quite understand what you said :/

  • I will formulate an answer. Then you will comment and I will edit the answer until you solve your problem. 1 instant.

  • I wanted the message to appear when the user is non-existent: Incorrect/Non-existent User or Password.

  • What it indicates is that you are having problems to pass the values of your form to this page. Have how to post your form?

  • I updated the question.

  • Updated response. Now everything should work!

Show 2 more comments

2 answers

2


but a blank screen appears on the page

Most likely to fall into this condition:

if (isset($_POST['email']) && isset($_POST['senha'])) {

I’m a beginner, and I couldn’t quite understand what you said

The code waits to be passed via post the values of email and senha. If not, it skips this whole block, which incidentally, lacks the closure of this condition (}).

In order to test, you can put a counter-condition in your code. It would look something like this:

if (isset($_POST['email']) && isset($_POST['senha'])) {

  $email = $_POST['email'];
  $senha = $_POST['senha'];

  $get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE email = '$email' AND senha = '$senha'");
  $num = mysqli_num_rows($get);

      echo $num;

} else echo "e-Mail e/ou senha não informados!";

That way your page should display the message if you have not passed the values of email and senha.

@Edit:

Notice well that in his HTML has these input:

<input type="text" name="usuario" placeholder="Usuário"><br>
<input type="password" name="senha" placeholder="Senha"><br>

And in the php script you are receiving these variables:

//...
// Aqui deveria ser "usuario" ao invés de "email"
if (isset($_POST['email']) && isset($_POST['senha'])) {
    //...
    $email = $_POST['email']; // Aqui deveria ser "usuario"
    $senha = $_POST['senha'];
    //...

The attributes name of the form must be compatible with keys searched in the variable $_POST.

@edit2:

Finally, the code concludes like this:

login.php:

<?php
    if(session_status() !== PHP_SESSION_ACTIVE) session_start();

        $dbInfo = array(
        'host' => 'localhost',
        'usuario' => 'root',
        'senha' => '',
        'db' => 'login'
    );

    $conn = mysqli_connect($dbInfo['host'], $dbInfo['usuario'], $dbInfo['senha'], $dbInfo['db']) or die(mysqli_error());

    if (isset($_POST['usuario']) && $_POST['usuario'] != '' && strlen($_POST['usuario']) >= 4 && isset($_POST['senha']) && $_POST['senha'] != '') {

        $usuario = $_POST['usuario'];
        $senha = $_POST['senha'];

        if(!($get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE nome = '$usuario' AND senha = '$senha';"))){
            echo "Erro na consulta: ".mysqli_error($conn);
            die(); // Para toda a execução do código.
        }
        if(mysqli_num_rows($get) == 1) {
            $_SESSION['logado'] = true;
            echo "Login efetuado com sucesso!";
        } else {
            echo "Falha ao efetuar o login";
        }

    } else echo "Usuário e/ou senha não informados.";

    // Logout:
    //unset($_SESSION['logado']);

?>

index php.:

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="login.php" method="post">
            <input type="text" name="usuario" placeholder="Usuário" required="required" minlength="4"><br>
            <input type="password" name="senha" placeholder="Senha" required="required"><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

Structure of the database (Mariadb):

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| nome  | varchar(100) | NO   |     | NULL    |                |
| senha | varchar(100) | NO   |     | NULL    |                |
| adm   | int(10)      | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
  • Little brother, okay, it worked, but as much as the login is right, the message appears :/

  • Okay, fixed, but little brother, I wanted to return the variable one, if the user is non-existent as it is in the code " echo $num", but the page does not appear anything

  • I fixed the code.

1

If in PHP it is isset($_POST['email'] then in HTML should be <input type="text" name="email" placeholder="email"> which is the most suggestive.

Now nothing inpede of HTML be <input type="text" name="usuario" placeholder="Usuário"> but in PHP should be isset($_POST['usuario']

<?php

$conn = mysqli_connect("localhost","USUARIO","SENHA",Nome_DB");

if (isset($_POST['email']) && isset($_POST['senha'])) {

  $email = $_POST['email'];
  $senha = $_POST['senha'];
  
  $get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE email = '$email' AND senha = '$senha'");
  $num = mysqli_num_rows($get);

      echo $num;
}
 ?>
 
 <!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="email" placeholder="email"><br>
            <input type="password" name="senha" placeholder="Senha"><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

From what you can see, you didn’t just want to know what was the mistake in your question, which was given in a comment of mine, already deleted. I will post you a complete and safe answer so that you have a good learning.

1 - Be judicious when building your SELECT statement, because the more data is read from the tables, the longer it will run. Especially when the database server is separated from the application server, because the data will have to pass through the network between the two.

Make it a habit to always specify the columns you will need when mounting your SELECT.

2 - <input type="email"> validates the field to ensure that the entered data is in fact a valid email address.

3 - required is a Boolean attribute used to indicate that a determining form field is mandatory for sending the form. When adding this attribute to a form field, the browser forces the user to enter data in that field before submitting the form.

4 - Avoid SQL Injection using Prepared Statements in PHP.

One of the biggest vulnerabilities of websites, the SQL injection (SQL Injection) is also, in the case of PHP, one of the easiest to prevent. Unfortunately, many do not take proper precautions and end up having their data compromised.

In the example I will use prepared statements using the extension PDO of PHP

In PHP, the Mysqli extension also supports prepared statements, but it’s better to use PDO because it makes it easier to migrate to other banks, as well as providing a concise API between them.

<?php

$servername = "localhost";
$username = "USUARIO";
$password = "SENHA";
$dbname = "Nome_DB";


if(isset($_POST['submit'])){

    if ( (isset($_POST['email']) && !empty($_POST['email'])) &&  (isset($_POST['senha']) && !empty($_POST['senha'])) ) {
    
      $email = $_POST['email'];
      $senha = $_POST['senha'];
    
        try{
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            // define o modo de erro do PDO para exceção
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        
            $stmt = $conn->prepare("SELECT email, senha FROM usuarios WHERE email= :email and senha = :senha");
             $stmt->bindParam(':email', $email,  PDO::PARAM_STR);
             $stmt->bindParam(':senha', $senha,  PDO::PARAM_STR);
             $stmt->execute();
             
             $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
             
             $count =  count($users);
        
                echo $count;    
        
        }

            catch(PDOException $e)
            {
            echo $sql . "<br>" . $e->getMessage();
            }
        
        $conn = null;
    
    }else{
        echo "Os dois campos são obrigatorios";
    }

}

?>

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="email" name="email" placeholder="email" required><br>
            <input type="password" name="senha" placeholder="Senha" required><br>
            <input type="submit" value="Login" name="submit">
        </form>
    </body>
</html>

5 - Why client-side (Front-end) and server-side validation (Back-end)?

Validating data being sent by the user only in javascript is not enough because of:

  • If the user disables javascript, you may end up with invalid data on the server

  • Because the front end is accessible in the browser. And every code there could end up being altered by someone with advanced knowledge and bad intentions. The Javascript code can be perfectly changed and so the validation can be circumvented.

  • server validations make a site less susceptible to malicious robots

In short... it is worth taking precautions against all these unknown agents, making the validation on the server (which is the most trusted agent) the main one... and in javascript, as a validation agilizer, because it does not need to go on the server.

6 - - Try/catch block serves for handling exceptions, handling codes that may not be fully met and generating some exception/error.

Try can recover errors that may occur in the code provided in your block. Catch in turn handles errors that have happened.

Should be used preferably when the developer has no way to guarantee that the code will run successfully.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.