The way to solve your problem definitively would be to implement queries prepared , since sending this query $query = ("CALL validaingreso('$varusr','$varpwd')");
to run directly is a serious security hole.
Let's see how to implement prepared queries in this case, explaining two possible ways to do it: using the procedural style (the one you implement in your code) and the object-oriented style (which is more modern and more understandable). Anyway, both work the same.
A. Procedural style
$varusr = $_POST['usr'];
$varpwd = $_POST['pwd'];
$query = ("CALL validaingreso(?,?)");
$stmt = mysqli_prepare($enlace, $query);
mysqli_stmt_bind_param($stmt, 'ss', $varusr, $varpwd);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
echo $row_cnt = mysqli_num_rows($stmt);
mysqli_stmt_close($stmt);
B. Object oriented style
$varusr = $_POST['usr'];
$varpwd = $_POST['pwd'];
$query = ("CALL validaingreso(?,?)");
$stmt = $enlace->prepare($query);
$stmt->bind_param('ss', $varusr, $varpwd);
$stmt->execute();
$stmt->store_result();
echo $row_cnt = $stmt->num_rows();
$stmt->close();
Brief explanation of the code
- In the SQL statement we substitute the variables that were previously passed directly by placeholders
?
. This is the first step to neutralize the attack
- Then we use
prepare
to tell the handler to prepare that query for us.
- Then we pass the values separately by
bind_param
. This is the second step to neutralize the injection. The ss
in the code means that the two columns used in this case are of type VARCHAR
in the database. If for example any of them were of type INT
we would have to put a i
instead of the s
. It is also important to point out that in bind_param
the variables must be put in the order that corresponds to them in $query
. And the same applies to the type of data.
- When we have everything ready, we invoke
execute
to finish the job.
- The PHP Manual states that, when using prepared queries, if we want to get the total of rows returned, we must first invoke
store_result
.
- Finally, we close the variable
$stmt
.