I'm trying to login using the fetch API, in which I get the data from the login form and pass it body
to this method.
In javascript I have the following:
const frm_login = document.getElementById('login_form');
frm_login.addEventListener('submit', (e) => {
e.preventDefault();
if (camposLogin.usuario && camposLogin.passw) {
var formdataL = new FormData(frm_login);
fetch('usuario.php', {
method: 'POST',
body: formdataL
})
.then(res => res.json())
.then(dataU => {
console.log(dataU);
)};
} else {
document.getElementById('formulario__mensaje-Login').classList.add('claseVisible');
setTimeout(() => {
document.getElementById('formulario__mensaje-Login').classList.remove('claseVisible');
}, 4000);
}
}
in the php I have it structured in a class where I make a function which will be called by another file with a php extension to make the query and that is where the variables obtained from the form arrive.
User class:
<?php
require "connection/Connection.php";
class Usuario {
public function logIn($login_usuario, $login_passw) {
$db = new Connection();
$query = "SELECT codigo, nom_usu, cod_tipo_usu FROM usuario WHERE nom_usu = '$login_usuario' AND pass_usu = '$login_passw'";
$resultado = $db->query($query);
$datosU = [];
if ($resultado->nums_rows) {
$row = $resultado->fetch_assoc();
while($row = $resultado->fetch_assoc()) {
$datosU[] = [
'codigoUsu' => $row['codigo'],
'nomUsu' => $row['nom_usu'],
'tipoUsu' => $row['cod_tipo_usu']
];
}
}
return $datosU;
}
}
?>
<?php
require "models/Usuario.php";
$usuario = [];
if (isset($_POST['login_usuario']) && isset($_POST['login_passw'])) {
$login_usuario = $_POST['login_usuario'];
$login_pass = $_POST['login_passw'];
$tabla_usuario = new Usuario();
$usuario = $tabla_usuario->logIn($login_usuario, $login_passw);
}
echo json_encode(['dataUsu' => $usuario]);
?>
I understand that from what is noted in the variables, I should not record the passwords in a textual way but as it is a practice I have left it that way since then I will proceed to the improvement related to this of the passwords; in relation to the code is there an error? since I executed it and tried to see it in the console but what I got is thatdataUsu se encuentra vacio
The methods
fetch_
move the pointer to the next row of results each time you apply them . So what is happening now in your code is the following:So, if you expect a single row, you can apply
fetch_
without any loop, because loops are used when you expect more than one row, precisely to move the pointer as long as there are rows .Other than that, you're doing
while
the same thing inside thefetch_assoc
, which is returning the data in the form of an associative array , so you don't have to do this:Here you should ask yourself, if these names were convenient for you:
codigoUsu
,nomUsu
andtipoUsu
, why didn't you name your columns like this in the table? Well, well, it's not that serious. You can solve it by using aliases in the SQL query as we will see.Since the code is confusing (it's not clear if you expect more than one row), I'll show you two possible solutions:
1. If you expect a single queue
Put a
LIMIT 1
to your query and read directly applyingfetch_
, you don't need anything else.NOTE that here I have opted for an organized style, according to which I have put in
$mData
a keystatus
that will betrue
when data is found and that data will be in a keydata
, instead, when there is no data, itstatus
will befalse
and there will be a keymsg
with a message of mistake. This is useful if you want to implement an error handling policy, which is essential in a self-respecting program.This practice should be extended to the other part of the code where you receive the POST data. Here we will also give coherence to the code, as said in the previous paragraph:
Now, on the client, you consume the response like this:
2. If you wait for several queues
You naturally remove the
LIMIT 1
from your query, and in this case you should actually read into awhile
.Everything else is the same, the only thing that would change would be the way of reading the response in case there is data, because in this case it
data
will be an array with all the rows found, and you must take it into account when using the data like this structured.Postscript
Your queries are vulnerable to SQL injection attacks , consider using prepared queries to prevent this serious security issue.