I am trying this:
$email=$conn->real_escape_string($_POST['email']);
$pwd=$conn->real_escape_string($_POST['password']);
$cons='SELECT * FROM Usuarios WHERE email=? AND password=?';
$stmt = $conn->prepare($cons);
if($stmt){
$stmt->bind_param("ss",$email,$pwd);
}
else{
echo "mm";
}
if($stmt->execute()){
$filas=$stmt->num_rows;
echo $stmt->error;
if($filas>0){
header('Location: consola.php');
}
else{
echo $filas;
echo $filas->error;
echo $filas->errno;
}
}
else{
echo $stmt->error;
echo "sss";
}
$conn->close();
It is a modification to another code that was more vulnerable to SQL injections so I decided to use prepared statements and bind_param
I suspect that the problem is $filas=$stmt->num_rows;
because when I give it it echo
prints 0 obviously that I verify that what I wrote in the inputs were in the table. I also want to know what other advice you have for the security of the code
There are several things in the code, I will comment on them in the order in which I find them and in the end I propose a solution:
real_escape_string
. Currently prepared queries are a powerful tool that do even what this function does not do in some cases. Yes, it is proven that in certain cases this function does not help you to escape from anything.POST
, we will useempty
for that, and a ternary operator.prepare
for any operation on the results.execute
, with evaluating the preparation it is enough. From there you will have at most0
rows if no data is found, but hardly a resultFALSE
. Also the logic of that part (where is evaluatedif($stmt->execute()){
) seems to be inverted.0
redirect to the page, and if not, it will print proper messages.There is something very important regarding the use of
num_rows
. The PHP Manual says that: The behavior ofmysqli_num_rows()
depends on whether buffered or unbuffered resultsets are used. In case of using them without buffer, it willmysqli_num_rows()
not return the correct number of rows until all the rows of the result have been retrieved . This means that to get the number of rows after the query is executed, you must buffer the results. For this, you can callstore_result()
before usingnum_rows
, otherwise it will always return0
rows even if there are results .As a note, if the only thing you want to know is if there are records, the correct thing would be to do a
SELECT COUNT(*)
, it is the most optimal way to check the existence of records in tables. I have not modified the query, so as not to alter your code too much. I mention it here so that you take it into account.I propose this code: