I am working with a login form in html / PDO PHP. As my PDO knowledge is almost zero I have been advancing in what the logic tells me and with stackoverflow. I have already made my connection and data capture and validated the information (I repeat as the logic has indicated, beginner's logic) but I have a problem when the page loads, it activates a validation alert and I cannot find how to make it only activate when send the form, unfortunately I can not work validation in a separate file, then the code:
<?php
session_start();
include ('pdoconnectexpo.php');
$usuario = $_POST['usuario'];
$contrasena = $_POST['pwd'];
if(isset($_POST['iniciar_sesion'])){
$query = 'SELECT id_usuario, usuario FROM "public".usuarios WHERE usuario=:usuario AND contrasena=:contrasena';
//Usuario
$registros = $conn2->prepare( $query ); //Preparamos la consulta
$registros->execute( array(":usuario" => $usuario,":contrasena" => $contrasena) ); //Le pasamos el valor al marcador, esto es un array por lo que soporta tanto valores requiera la query, separador por coma
$registros = $registros->fetchAll( PDO::FETCH_OBJ ); //convirtiendo el resultado en objetos para poder iterar en un ciclo.
if(!isset($registros[0]->usuario)){
echo "<script type=\"text/javascript\">alert(\"Usuario Errado o Contraseña Errada\");</script>";
}else{
// code...
$_SESSION['usuario'] = $usuario;
$_SESSION['id_usuario'] = $id_usuario;
header('Location: inicio.php');
}
}
?>
And below the php I call the following html code (I only place the form):
<form class="login100-form validate-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<span class="login100-form-title p-b-34">
Inicio de Sesión
</span>
<div class="wrap-input100 rs1-wrap-input100 validate-input m-b-20" data-validate="Type user name">
<input id="first-name" class="input100" type="text" name="usuario" placeholder="Usuario">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 rs2-wrap-input100 validate-input m-b-20" data-validate="Type password">
<input class="input100" type="password" name="pwd" placeholder="Contraseña">
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn">
Iniciar Sesión
</button>
</div>
</form>
The first thing is that you can optimize your query instead of 2 having 1;
So in your
HTML
login button create it of typesubmit
and assign it a name with the attributename
, this way you verify that this button is pressed;With this, it only remains to verify that when the button is pressed, it shows the alert;
combining all this you get like this;
HTML
I'll explain a little more, what we did was create a new element of type input, to send it to the server when the user sent the form, so we check that this element exists in the request for data to the server and we can be sure that this is only load when the form is submitted by
POST.