It's my first question in Stackoverflow so sorry if something is not quite right.
I started learning back-end development a few days ago.
Currently, I am working on an application with login capabilities.
From what I have learned so far, I should take a username and password input, then check if there is a match in a database and if there is I will log that person in.
However, in order to protect my web app from potential SQL injections, I need to use prepared statements or at least escape strings when building queries.
If I get user input, then I use a for loop to get username and password of each user and compare them to user input that is trying to log in.
That would seem to solve SQL injection danger since nothing is sent to the server, only compared to data inside the server.
Is this approach a lot slower or does it open other vulnerabilities?
Which method should be used to be better and safer?
This is the PHP code I am using:
$r = "SELECT * FROM users";
$result = mysqli_query($con, $r);
$rows = mysqli_num_rows($result);
for ($i = 1; $i <= $rows; $i++){
$checkQ = "SELECT * FROM users WHERE id = $i";
$r = mysqli_query($con, $checkQ);
$result = mysqli_fetch_assoc($r);
if ((isset($_POST["username"])) && (isset($_POST["password"]))) {
if (
($result["username"] == $_POST["username"])
&& ($result["password"]==$_POST["password"])
) {
$_SESSION["username"] = $_POST["username"];
mysqli_close($con);
header("Location: home.php");
}
}
}