Tá giving error but still the user is being registered [duplicated]

-5
<?php

if (isset($_POST['cadastro']) && $_POST['cadastro'] == "ok") {
    $usuario = $_POST['usuario'];
    $senha = $_POST['senha'];
    $nivel = $_POST['nivel'];
    $nome = $_POST['nome'];
    $email = $_POST['email'];

    $verificar_usuario = mysqli_query($conexao, "SELECT usuario FROM 
    up_users WHERE usuario = '$usuario'");

    if (mysqli_connect_errno()) {
        printf ( "Conexão falhou: %s/n",mysqli_connect_error());
    }

    if (mysqli_num_rows($verificar_usuario) >= 1) {
        echo "<div class=\"no\">Usuário não pode ser cadastrado pois 
        ele já existe!</div>";
    } else {
        $cadastra_usuario = mysqli_query($conexao, "INSERT INTO 
        up_users (usuario, senha, nivel, email, nome) 
        VALUES ('$usuario','$senha','$nivel','$email','$nome')");

        if (mysqli_connect_errno()) {
            printf ( "Conexão falhou: %s/n",mysqli_connect_error());
        }

        // O erro é aqui
        if (mysqli_num_rows($cadastra_usuario) >= 1) {
            echo "<div class=\"ok\">Usuário cadastrado com sucesso! 
            </div>";
        } else {
            echo "<div class=\"no\">Erro ao cadastrar o usuário! 
            </div>";
        }
    }
}

Error:

  

Warning: mysqli_num_rows () expects parameter 1 to be mysqli_result, boolean given in C: \ Program Files (x86) \ EasyPHP-Devserver-17 \ eds-www \ upprofessional \ admin \ user_cadastro.php on line 46   Error registering user!

I'm using num_rows wrong?

    
asked by anonymous 25.09.2018 / 15:27

2 answers

2

Since your command is a INSERT , mysqli_num_rows() will always return zero because it is used to count rows returned by SELECT . To find out the number of rows generated by a INSERT (or changed by UPDATE , or removed with DELETE ), use mysqli_affected_rows .

    
25.09.2018 / 16:40
0

This must be happening because the query does not return anything because that user does not exist. I suggest that before using mysqli_num_rows you should check that the $verificar_usuario variable is not null.

Your if will look like this:

if($verificar_usuario != null && mysqli_num_rows($verificar_usuario) >= 1)
{
    echo "<div class=\"no\">Usuário não pode ser cadastrado pois 
    ele já existe!</div>";
}
    
25.09.2018 / 16:04