Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am making a php login system, and I don't know what is going wrong

I have an html form passing data to this program:

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    $passcrypt = hash('sha256', $password);
    $conn = new mysqli('localhost', 'phpUser', 'phpPass', 'phpBase');
    $pass = "SELECT password FROM login WHERE username = '$username'";
    $result = $conn->query("SELECT password FROM login WHERE username = '$username'");
    $conn->close();
    if ($result == $passcrypt) {
        print 'logged in!';
    }else{
        print 'error <br />';
        print $passcrypt;
    }
?>

(those obviously aren’t my passwords)
and it isn’t working, and I have no idea why!!!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s obviously because you dont fetch any data. you need $result->fetch_assoc() to fetch the data.

<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passcrypt = hash('sha256', $password);
$conn = new mysqli('localhost', 'phpUser', 'phpPass', 'phpBase');
$pass = "SELECT password FROM login WHERE username = '$username'";
$result = $conn->query("SELECT password FROM login WHERE username = '$username'");
$result = $result->fetch_assoc()
$conn->close();
if ($result == $passcrypt) {
    print 'logged in!';
}else{
    print 'error <br />';
    print $passcrypt;
}
?>

Also, make sure to var_dump($result) after fetching it to test and debug the process to make sure all things going well.

Also, use the prepare statement to prevent SQL injection.

the code could be better this way:

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    $passcrypt = hash('sha256', $password);
    $conn = new mysqli('localhost', 'phpUser', 'phpPass', 'phpBase');
    $query = "SELECT password FROM login WHERE username = ? "; // SQL with parameters
    
    $stmt = $conn->prepare($query); 
    $stmt->bind_param("s", $username); // 's' for string
    $stmt->execute();
    $result = $stmt->get_result(); // get the mysqli result
    $result = $result->fetch_assoc(); // fetch data  

    if ($result['password'] == $passcrypt) {
        print 'logged in!';
    }else{
        print 'error <br />';
        print $passcrypt;
    }
    $conn->close();
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading