I'm doing a project for the school and I'm having some troubles with this login, I know how to do it in a different way, but I would like to learn how to do it this way.
I don't really know why its not working (some parts probably don't have any logic and is why its not working), it always says the error message "Invalid credentials" from the alert.
Here is my code:
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'loginFinal.php',
data: $(this).serialize(),
success: function(data) {
if (data === 'CORRECTO') {
window.location = 'index.php';
}
else {
alert('Invalid credentials');
}
}
});
});
});
</script>
</head>
<body>
<form id="loginform" method="post">
Username: <input type="text" name="username" id="username" value="">
Password: <input type="password" name="password" id="password" value="">
<input type="submit" name="loginsub" id="loginsub" value="Login">
</form>
</body>
</html>
And here is the PHP:
function Login() {
$success = false;
try {
$con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
$sql = "SELECT * FROM users WHERE username = ".$_POST['username']." AND password = ".$_POST['password']." LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
session_start();
session_regenerate_id();
$_SESSION['user'] = $_POST['username'];
session_write_close();
echo ('CORRECTO');
exit();
}
$con = null;
return $success;
}
catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
MYSQLI_orPDOAPI's