Simple MySQL login with PHP and AJAX requests

347
March 04, 2017, at 06:44 AM

I'm trying to create a very simple MySQL login function using PHP. The username and password are posted the PHP through AJAX. The AJAX function is:

function login(){
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
    $.ajax({
        url : "login.php",
        type : "POST",
        data : {
            username : user,
            password : pass
        },
        success : function(response){
            alert(response);
        },
        error : function(response){
            alert(response);
        }
    });
}

The login script:

$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//echo "Connected successfully";
$user = $_POST['username'];
$pass = $_POST['password'];

$query="SELECT * FROM Users WHERE email = '$user' AND password ='$pass' LIMIT 1";
$result = $conn->query($query);
$count = $result->num_rows;
if($count == 1){
     echo "success";
}else{
    echo "incorrect login details";
}
$conn->close();
?>

It seems that $count is always zero, even when the username and password are correct. I've verified that the username and password are being successfully retrieved in PHP.

An even simpler query, SELECT * FROM Users also returns a count of 0.

Attempting to echo or var_dump $result results in object Object being displayed.

Can anyone see any glaring issues with this code? A fresh set of eyes would be greatly appreciated.

Note: This simple function is not designed to be secure, hence the insecure query formatting.

Answer 1

I'd suggest changing the following to strings and running the PHP script. If the strings appear in your DB, you can then rule out if it's caused by the PHP script, in which case it will be the html and ajax elements.

//$user = $_POST['username'];
//$pass = $_POST['password'];
$user = 'userTest';
$pass = 'userPass';
Rent Charter Buses Company
READ ALSO
MySQL Cannot Add Foreign Key Constraint

MySQL Cannot Add Foreign Key Constraint

So I'm trying to add Foreign Key constraints to my database as a project requirement and it worked the first time or two on different tables, but I have two tables on which I get an error when trying to add the Foreign Key ConstraintsThe error message...

541
how to make a global MySQL connection method in Java

how to make a global MySQL connection method in Java

I'm trying to make a JavaFX application that require connection to MySQL DB and perform username and password checking(Login) and other CRUD applicationbelow is my Java class to connect and check the username and password

367