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.