Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mozew's avatar
Level 6

how to create md5 password in php and save to database?

I have an existing database with users, each users password is stored as an MD5 hash.

Im trying to create a login form using PHP (Which im very new too) only I cant seem to get it to work, I know my username and password is correct yet I still receive the error that its wrong, Have I got to convert my password input to MD5 before checking the username in the table?

I currently have...

if (isset($_POST['register'])){
    $name = $_POST['name'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    if ($password == $confirm_password) {
        $query = mysqli_query($db, "INSERT INTO users (name, username, password) VALUES ('$name', '$username', MD5('".$password."'))");
        
        //$query="INSERT INTO ptb_users (id,user_id,first_name,last_name,email )VALUES('NULL','NULL','".$firstname."','".$lastname."','".$email."',MD5('".$password."'))";
        echo 'OK.';
    } else {
        echo 'Error.';
    }
}
0 likes
6 replies
Nash's avatar

You need to check if the (hashed) password in your db matches the hashed value of the input. However, you should not store passwords as md5, it's not secure. Also, you should use prepared statements (and preferably PDO) to protect against SQL injections.

D9705996's avatar

First thing - md5 is a really bad choice for a hashing algorithm for passwords. Its insecure as highlighted in teh PHP function documentation.

If I had to implement your approach I would let php deal with the hashing of your password

e.g.

$password = md5($password);
$query = mysqli_query($db, "INSERT INTO users (name, username, password) VALUES ('$name', '$username','$password')");
 

You can pretty much achieve what you are asking with php artisan make:auth

This StackOverflow might help you import your existing database into a laravel application and upgrade the hashing algorithm when you users first login.

shez1983's avatar

@D9705996 how is php md5() any securer than MySQL if they are both MD5?

OP: if you are using laravel then it has bcrypt() function pass it a string and it can create a secure hashed password...

D9705996's avatar

@shez1983 -php md5 isnt more secure, my comment was more related to if the OP has an existing DB with md5 hashed passwords having the MD5 sum in your code can be used to determine if a rehash is required (as per Stack Overflow link)

It also cleared up the SQL statement if OP decides to carry on with md5 but to be clear

Do Not Use MD5 to store hashed data, EVER

rawilk's avatar

Like the others mentioned, don't used md5, use bcrypt instead.

$password = bcrypt($_POST['password']);
1 like
cmdobueno's avatar

md5 is the devil. It is about as secure as a plain string now... just saying.

Please or to participate in this conversation.