Aplex Aplex - 6 months ago 51
PHP Question

sqlite login form having trouble getting it to work

im trying to check if the username and the password put into the input fields are stored in my database. And if there is not then it should give an error message. I have a user in my database atm:
username: alexander

password : alexalex


But however when I run my code to login it doesn't say that it is the right login.

<?php
try{
$db = new PDO('sqlite:users.db');
}
catch(PDOException $err){}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];

try{
$sql = "SELECT * FROM players WHERE username='$username' AND password='$password'";
$st = $db->prepare($sql);
$st->execute();
if($st->fetchColumn() == 1){
//SUCCES LOGIN
}else{
//FAILED LOGIN
}
}catch(PDOException $err){}
}
...HTML CODE...
<form action="" method="POST" class="login-form">
<input type="text" id="one" name="username" placeholder="Username">
<input type="password" id="two" name="password" placeholder="Password">
<input type="submit" value="LOGIN" class="three">
</form>


Very thankful for anyone who can solve this login!

Answer

As noted by Jay Blanchard:

if($st->fetchColumn() == 1)

where you should have been using fetch().

However, that would still fail you with this conditional statement once changed to fetch():

if($st->fetch() == 1)

as that checks if there is only 1 and needs to also satisfy both conditions.

If there is more than one row of the same username, that will also fail you.

Therefore either use >1 or >=1.

Also as stated in comments. Use a prepared statement and password_hash() if this is a live site or intended to go live.

It's just a matter of time before your database gets hacked.