Query number of MySQL returns

1

I'm 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 manually done within phpMyAdmin I get success with my query.

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

Since there is no record with name "name" and nor with pass "password.

However, when doing the check in PHP it always returns me one (even those data not existing 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 the incorrect data, that is putting username and pass with nonexistent values, however every time I send the form it returns me the data of the the only registered user who is the "Admin".

    
asked by anonymous 03.01.2015 / 16:21

1 answer

1

Your result is normal. To get the result you expect, you should 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 the "count" but the result number. So, if you have for example 14878 data in the table, the query will return a number only, with a value of 14878. And mysqli_num_rows will return 1.

    
03.01.2015 / 16:39