Encrypting a password field with PHP in MYSQL

Hi all,
First of all I am new to PHP and this forum hope I am in the correct area.
What I want to do is have a HTML form with a password field.
Then PHP encrypts this entry with MD5 so it can be submitted to a MYSQL database.
So when anyone looks up the entry stored in the database it will be encrypted and unreadable.
:blush: JayminYoung

Welcome to SitePoint JayminYoung. :slight_smile:

MySQL has a built in SHA1 function you can use here, itโ€™s advisable to use this over MD5.


<?php
$sql = sprintf(
  "INSERT INTO table (username, password) VALUES ('%s', SHA1('%s'));",
  mysql_real_escape_string($_POST['username']),
  mysql_real_escape_string($_POST['password'])
);

$res = mysql_query($sql);

If any of the functions Iโ€™ve used above are new to you, check out [fphp]sprintf[/fphp], [fphp]mysql_real_escape_string[/fphp] and [fphp]mysql_query[/fphp].

You can then find this user with the following bit of complementary code:


$sql = sprintf(
  "SELECT username FROM table WHERE username = '%s' AND password = SHA1('%s') LIMIT 1;",
  mysql_real_escape_string($_POST['username']),
  mysql_real_escape_string($_POST['password'])
);

$res = mysql_query($sql);

AnthonySterling,
thank you for your quick reply, I will have a try and see how it works