SELECT does not work on a database with PHP

1

I'm trying to make a simple login. The idea is to look in the database for the user and password.

The fact is that I have a SELECT that should take the rows with name and user that match those previously entered by the user.

The SELECT does not take any row, that is, it is not the fault of SELECT but of the statement to connect to the database.

Code validar.php , where the failure occurs:

<?php
        include 'serv.php';
        if(isset($_POST['login'])){
            $usuario = $_POST['user'];
            $pw = $_POST['pw'];
            $log = mysqli_query("SELECT * FROM noticiasBD WHERE user='$usuario' AND pw='$pw'");
            echo "tenemos: $log";
            echo '<script> alert("tenemos: $log");</script>';

            if (mysqli_num_rows($log)>0) {
                $row = mysql_fetch_array($log);
                $_SESSION["user"] = $row['user']; 
                echo 'Iniciando sesión para '.$_SESSION['user'].' <p>';
                echo '<script> window.location="panel.php"; </script>';
            }
            else{
                echo '<script> alert("Usuario o contraseña incorrectos.");</script>';
                echo '<script> window.location="index.php"; </script>';
            }
        }
    ?>

Here I have the form where I call validad.php . It's called index.php :

<?php
session_start();
include 'serv.php';
if(isset($_SESSION['user'])){
echo '<script> window.location="panel.php"; </script>';
}
?>

<h1 class="h1" style="color:white">Login</h1>
        <form method="post" action="validar.php">
            <input type="text" class="form-control" name="user" autocomplete="off" required><br><br>
            <input type="password" class="form-control" name="pw" autocomplete="off" required><br><br>
            <input type="submit" class="btn btn-success" name="login" value="Entrar">
        </form>

And I connect to the database from serv.php , which does not fail:

<?php
$conect = mysqli_connect('localhost', '--', '--', 'c1jormacolBD')
  or die('Error: ' . mysqli_connect_error());

Image from phpMyAdmin:

It connects well to the database but not to the table in question.

    
asked by CMorillo 24.08.2017 в 14:57
source

1 answer

3

The main problem that you are suffering is not to pass the connection obtained with mysqli_connect to the function mysqli_query() :

$log = mysqli_query($conect, "
  SELECT *
  FROM noticiasBD
  WHERE user='$usuario' AND pw='$pw'
");

Also, you are forgetting to use session_start to start the sessions, however you try to use them to store the logged in user in:

$_SESSION["user"] = $row['user'];

Depending on the error you mention in your edition, it is likely that in another part of the code (the line numbers do not match, it is likely that you have omitted code) you have logged in, so we can use session_status to find out if it was done or not:

if (session_status() === PHP_SESSION_DISABLED) {
  session_start();
} 

You are getting the result with the function mysql_fetch_array instead of mysqli_fetch_array and, in addition, you would get values with numerical index ( $row[0] , $row[1] ), non associative ( $row['user'] , $row['pw'] ):

$row = mysql_fetch_array($log);

Finally, remember THE IMPORTANCE OF PROTECTING YOU FROM SQL INJECTION Use of mysqli_real_escape_string .

This would be your fixed code:

<?php
/* Si vamos a usar sesiones debemos iniciarlas aquí también */
if (session_status() === PHP_SESSION_DISABLED) {
  session_start();
} 
include 'serv.php';
if (isset($_POST['login'])) {
    /* ¡¡NO OLIVIDES hacer esto para evitar inyección SQL!!! */
    $usuario = mysqli_real_escape_string($conect, $_POST['user']);
    $pw = mysqli_real_escape_string($conect, $_POST['pw']);
    $log = mysqli_query($conect, "
      SELECT *
      FROM noticiasBD
      WHERE user='$usuario' AND pw='$pw'
    ");
    /* Debemos comprobar si hubo un fallo en la consulta */
    if ($log === false) {
        die('ERROR SQL: ' . mysqli_error($conect));
    }
    $row = mysqli_fetch_assoc($log);
    if ($row !== false) {

        /* Esto no funciona sin el "session_start()" inicial */
        $_SESSION["user"] = $row['user'];
        echo '<p>Iniciando sesión para ' .
          htmlspecialchars($_SESSION['user']) . '</p>';
        echo '<script> window.location="panel.php"; </script>';
        /* Probablemente esto sea mejor que javascript */
        header('Location: panel.php');
    } else {
        echo '<script> alert("Usuario o contraseña incorrectos.");</script>';
        echo '<script> window.location="index.php"; </script>';
    }
}

Also, I have added error control to handle SQL errors in the query and I have detected if the user exists or not getting the result of the query with mysqli_fetch_assoc (it will be worth true if it was found or false , there are no more records, if it was not).

Finally, it is a bad practice to store plain text passwords in the database. If someone manages to access that data (for now you were already allowing them to do so by suffering a bug from SQL injection a>) you would expose the access data and it would be very easy to impersonate the identities of your clients.

    
answered by 25.08.2017 / 09:29
source