I have a database of usernames and passwords. I need to create a “Forgot password” function and have it search the table for a username and return that user’s password. Then I would like it to send an email saying the name and password.
Here is my working code for querying the database for a specific user:
<?php
session_start();
include "config.php";
if($_POST['nameQuery']) {
$query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
//User exists
echo '1';
} else {
mysql_query($query);
//User does not exist
echo '0';
}
}
?>
First thing’s first: you might want to make sure that you won’t get
SQL-injectedvia your login, as you’re literally injecting the user input into your query… big no-no.Swap this:
…for this:
Next up is what you asked for: a way to get both the users username and password. While I don’t recommend that you actually store the password in plaintext for everyone to view, it’s a decision you have to make on your own.
This snippet will do the deed:
Edit: Adding password recovery-functionalityFor the password recovery-functionality you requested below, you can try something like this:
recover_password.php:Note that I haven’t had time to actually test the code, but I think it’ll work just fine with some minor adjustments. Oh, before I forget, you’ll need to add the following table to the DB:
Table structure for table
myRequestsGood luck!