Refer to number of Mysql returns

Asked

Viewed 549 times

1

I am trying to do a check in a database to check if there is a certain value, which should return me 0 or 1.

In the query made manually inside the phpMyAdmin get success with my query.

SELECT COUNT(*) FROM users WHERE name = 'nome' AND pass = md5('senha') LIMIT 1;

Since there is no record of name "name" and not with the pass "password.

However, when checking in PHP it always returns me one (even though this data does not exist in the database).

<?php

if( !isset($_POST['login']) ) die('Erro');

require_once('../config.php');


if( !isset($_POST['username']) || !isset($_POST['password']) ) {
    exit("Erro: Faltam dados no formulário.");
}
else if( empty($_POST['username']) || empty($_POST['password']) ) {
    exit("Erro: O formulário não pode estar vazio.");
}
else {

    $db_data = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
    $username = $_POST['username'];
    $password = $_POST['password'];
    $total = 0;
    $sql = "SELECT COUNT(*) FROM users WHERE name = '$username' AND pass = md5('$password') LIMIT 1;";
    $query = mysqli_query($db_data, $sql);

    if($query) {
        $total = mysqli_num_rows($query);
    }
    else {
        die("Erro ao realizar a consulta.");
    }

    if($total === 1) {

        $sql = "SELECT id, nickname, level, active  FROM users WHERE name = '$username';";
        $query = mysqli_query($db_data, $sql);
        $num = mysqli_num_rows($query);

        if($num > 0) {

            $row = mysqli_fetch_array($query, MYSQLI_ASSOC);
            $nickname = $row['nickname'];
            $id = $row['id'];
            $level = $row['level'];
            $active = $row['active'];

            echo "<strong>Nome:</strong> $nickname<br>";
            echo "<strong>ID:</strong> $id<br>";
            echo "<strong>Nível:</strong> $level<br>";
            echo "<strong>Ativo:</strong> $active<br>";
        }

        mysqli_close($db_data);

    }
    else{
        die('erro');
    }
}

Yes, it is a code for studies only... I am sending the form with incorrect data, that is to say putting username and pass with non-existent values, but every time I send the form it returns the data of the only registered user that is the "Admin".

1 answer

1


Your result is normal. To get the result you expect, you must do it this way:

 $query_select = "SELECT count(*) as total FROM TAB";

et then read the result this way (after mysqli_fetch_array)

  $numero_de_dados = $row['total'];

In the case of your code, the result you have is not the result of "Count" but the result number. So, if you have for example 14878 data in the table, the query will return ONE number only, with a value of 14878. And the mysqli_num_rows will return 1.

Browser other questions tagged

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