mysqli_query SELECT can not find items

0

I have a problem, in a login in php I have a line of code that checks if the user and password are correct, if so, the code continues. The error is that I enter the username and password that exist in the DB and it says as if they did not exist.

$result = mysqli_query($link,"SELECT user, pass FROM usuarios WHERE user=    $username AND pass= $password");

if($result && mysqli_num_rows($result) > 0)
{
   // Login OK, continuar con el codigo.
}
else
{
   // Introduciendo un usuario y password que existen me salta este error todo el rato.
   echo 'Usuario o password no existe';
}
    
asked by marc 23.09.2016 в 17:50
source

2 answers

1

You must use prepared statements to avoid ingesting SQL code.

contantes.php

define('DB_HOST','TU IP');
define('DB_USERNAME','USUARIO');
define('DB_PASSWORD','CONTRASEÑA');
define('DB_NAME','BASE DE DATOS');

DBConnection

include_once 'Constantes.php';
class DBConnection {
 private $connection;
 public function connectMySQLi(){
     mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
     try {
         $this->connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
     } catch (mysqli_sql_exception $e) {
         echo "Falló al hacer la conexion: ".$e->getMessage();
     }
     //retornamos el link de conexion
     return $this->connection;
 }
}

Send to call

require_once 'DBConnection.php';
    $bd = new DBConnection();
    //realizamos la instancia de la conexion
    $connection = $bd->connectMySQLi();
    //hacemos el query
        $query = "SELECT * FROM usuarios WHERE username = ? AND pass= ?";
        $stmt = $connection->prepare($query);
        $stmt->bind_param('ss', $username, $password);
        $stmt->execute();
        //obtenemos los resultados
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if (count($result) > 0) {
            return "Acceso correcto";
        } else {
            return "Usuario no encontrado";
        }
    
answered by 25.09.2016 в 15:12
0

The query is necessary to enclose the variables in single quotes.

like that.

"SELECT user , pass FROM usuarios WHERE user='$username' AND pass='$password'"

Luck.

    
answered by 23.09.2016 в 17:56