I would like you to help me with this error: mysqli_num_rows () expectsparameter1tobemysqli_result, boolean given

0
<?php

$alert="";
    if (!empty($_POST)) {
        if (empty($_POST['usuario']) || empty($_POST['contraseña'])) {

            $alert="Ingrese su usuario y su clave";

        }else{


        require_once "conexion.php";

        $user = $_POST['usuario'];
        $pass = $_POST['contraseña'];

        $query = mysqli_query($conection,"SELECT * FROM datos WHERE usuario='$user' AND contraseña='$pass'");

        $result = mysqli_num_rows($query);

        if ($result>0) {

            $data = mysqli_fetch_text($query);
            session_start();
            $_SESSION['active'] = true;
            $_SESSION['idUser'] = $data['id'];
            $_SESSION['nombre'] = $data['usuario'];



        }



        }

    }

?>




<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>


<center>
    <form method="post">
        <h1>Iniciar Sesion</h1>
        Nombre de Usuario:<input type="text" name="usuario" placeholder="Nombre de usuario" required><br><br><br>

        Contraseña<input type="password" name="contraseña" placeholder="Ingrese Contraseña" required><br>

        <input type="submit" value="Ingresar">
        <input type="reset" value="Limpiar">

        <p class="alerta"> Mensaje</p>
</center>
    </form>

</body>
</html>
    
asked by juan flores perez 02.11.2018 в 02:16
source

1 answer

2

I welcome you.

The code you present has some inconsistencies and some controls are missing. I will list them in order of appearance and then I will propose a possible solution:

  • Never declare variables before knowing if you are going to use them
  • It is not necessary to first evaluate all $_POST
  • I think the condition to execute the query should not be if there is data in usuario O in contraseña , but if there is data in usuario and in contraseña , since both values are used in WHERE
  • Since the query is failing, we will also check the connection
  • Your code is insecure, you should use queries prepared to avoid SQL injection attacks (I recommend you read about it when you can, it's important)
  • As far as I know, mysqli does not have a mysqli_fetch_text method ...!

Seen that, let's go with the code:

<?php
    /*
        *Usamos ternarios para verificar el estado del POST
        *y de paso guardamos los datos en variables
        *para usarlas más adelante si fuera necesario
    */  
    $usuario =(empty($_POST['usuario']))    ? NULL : $_POST['usuario'];  
    $password=(empty($_POST['contraseña'])) ? NULL : $_POST['contraseña']; //Evitaría usar ñ     
    /*
        *Cambiamos la lógica para no hacer demasiado lío
    */
    if ($usuario && $password) {
        require_once "conexion.php";
        if ($conection){
            /*
                *Escribimos una consulta preparada
                *para evitar el riesgo de Inyección SQL
                *El código varía un poco, pero es necesario hacer esto
                *para no poner en riesgo los datos
            */
            $sql="SELECT id, usuario FROM datos WHERE usuario=? AND contraseña=?";
            if ($stmt = mysqli_prepare($conection, $sql)) {
                /*
                    *Pasamos a $stmt los datos aparte
                    *indicando con las ss con son datos de tipo cadena - (s)tring
                    *Luego ejecutamos 
                */
                mysqli_stmt_bind_param($stmt, "ss", $usuario,$password);
                mysqli_stmt_execute($stmt);
                /*
                    *Indicamos dos variables para cada columna del resultado
                    *que usaremos para ponerlas en la variable de sesión
                */
                mysqli_stmt_bind_result($stmt, $id, $usr);
                mysqli_stmt_store_result($stmt);
                $totalFilas=mysqli_stmt_num_rows($stmt);

                if ($totalFilas>0){
                    while (mysqli_stmt_fetch($stmt)) {
                        session_start();
                        $_SESSION['active'] = true;
                        $_SESSION['idUser'] = $id;
                        $_SESSION['nombre'] = $usr;
                    }

                }else{
                    echo "No se encontraron filas";
                }

            }else{
               echo "Error en la consulta: ".mysqli_error($conection);
            }

        }else{
            echo "No hay conexión disponible";
        }


    }else{
        echo "Ingrese su usuario y su clave";
    }
?>

I have tried to explain everything in comments within the same code. And you have a controlled program at all times, which will duly inform about any eventuality.

I hope it serves you.

    
answered by 02.11.2018 в 11:32