Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6248301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T13:01:56+00:00 2026-05-24T13:01:56+00:00

I have a database of usernames and passwords. I need to create a Forgot

  • 0

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'; 
}
}
?>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T13:01:56+00:00Added an answer on May 24, 2026 at 1:01 pm

    First thing’s first: you might want to make sure that you won’t get SQL-injected via your login, as you’re literally injecting the user input into your query… big no-no.

    Swap this:

    $query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";  
    

    …for this:

    $query = sprintf(
        'SELECT * FROM myDatabase WHERE name = \'%s\'', 
        mysql_real_escape_string($_POST['nameQuery'])
    );
    

    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:

    <?php
        //Get the data from the DB
        $query = sprintf(
            'SELECT * FROM myDatabase WHERE name = \'%s\'', 
            mysql_real_escape_string($_POST['nameQuery'])
        );
        $result = mysql_query($query);
        $user_info = mysql_fetch_assoc($result);
    
        //Check if it's valid
        if( isset($user_info['name']) ) {
    
            //Construct the message
            $message = 'Your username is: ' . $user_info['name'] . "\n"
            $message .= 'Your password is: ' . $user_info['password'] . "\n";
    
            //Send it to the appropriate email
            $status = mail(
                $user_info['email'], 
                'Password recovery for ' . $user_info['name'], 
                $message
            );
    
            //Check if it actually worked
            if( $status ) echo 'Mail sent. Check your inbox. Login again. Thank you.';
            else echo 'The password recovery couldn\'nt be sent. Please try again later.';
    
        } else { 
    
            echo 'No user found with the supplied username.', 
                'Please try again (with another username)';
    
        }
    ?>
    

    Edit: Adding password recovery-functionality

    For the password recovery-functionality you requested below, you can try something like this:

    recover_password.php:

    <?php
        session_start();
    
    
        //mysql_connect()-here
    
        //Initalize the variable
        $do_update_password = false;
    
        //Grab the  token
        $token = isset($_REQUEST['token'])? $_REQUEST['token'] : '';
        $is_post_request = isset($_POST['update_pwd'])? true : false;
        $is_recovery_request = isset($_POST['request_recovery'])? true : false;
        $message = '';
    
        //Check if we're supposed to act upon a token
        if( $is_recovery_request ) {
    
            //Grab the email
            $email = isset($_POST['email'])? $_POST['email'] : '';
    
            //Create the query, execute it and fetch the results
            $sql = sprintf(
                'SELECT `user_id` FROM myDatabase WHERE `email` = \'%s\'',
                mysql_real_escape_string($email)
            );
            $result = mysql_query($sql);
            $user_info = mysql_fetch_assoc($result);
    
            //Validate the response
            if( isset($user_info['user_id') ) {
    
                //Let's generate a token
                $date = date('Y-m-d H:i:s');
                $token = md5($email . $date);
    
                //Create the "request"
                $sql = sprintf(
                    'INSERT INTO myRequests (`user_id`, `token`, `date`) VALUES (\'%s\', \'%s\', \'%s\')',
                    $user_info['user_id'],
                    mysql_real_escape_string($token),
                    $date
                );
                $result = mysql_query($sql);
    
                //Validate
                if( mysql_affected_rows($result) == 1 ) {
    
    
                    //Construct the message
                    $message = 'Your username is: ' . $user_info['email'] . "\n"
                    $message .= 'Please click on the following link to update your password: http://yoursite.com/request_password.php?token=' . $token . "\n";
    
                    //Send it to the appropriate email
                    $status = mail(
                        $email, 
                        'Password recovery for ' . $email, 
                        $message
                    );
    
                    //Check if it actually worked
                    if( $status ) {
    
                        echo 'Mail sent. Check your inbox. Login again. Thank you.';
    
                    } else {
    
                        echo 'The password recovery couldn\'nt be sent. Please try again later.';
    
                    }
    
                } else {
    
                    $message = 'The DB-query failed. Sorry!';
    
                }
    
            } else {
    
                $message = 'The specified e-mail address could not be found in the system.';
    
            }
    
        } elseif( $token != '' ) {
    
            //Check so that the token is valid length-wise (32 characters ala md5)
            if( !isset($token[31]) || !isset($token[32])  ) { 
    
                $message = 'Invalid token!';
    
            } else {
    
                //Construct the query and execute it
                $sql = sprintf(
                    'SELECT `user_id` FROM myRequest WHERE `token` = \'%s\'', 
                    mysql_real_escape_string($token);
                );
                $result = mysql_query($sql);
    
                //Fetch the rows
                $request_info = mysql_fetch_assoc($result);
    
                //Check for a valid result
                if( isset($request_info['user_id']) ) {
    
                    $message = 'Update your password below.';
                    $do_update_password = true;
    
                } else {
    
                    $message = 'No record found for the following token: ' . $token);
    
                }
            }
        } elseif( $is_post_request ) {
    
            //Grab the new password
            $password = isset($_POST['password'])? $_POST['password'] : '';
    
            //Construct the query
            $sql = sprintf(
                'UPDATE myDatabase SET `password` = \'%s\' WHERE `user_id` = ( SELECT `user_id` FROM myRequest WHERE `token` = \'%s\' )', 
                mysql_real_escape_string($password),
                mysql_real_escape_string($token)
            );    
    
            //Execute it, and check the results
            $result = mysql_query($sql);
            if( $result !== false ) {
    
                //Did we succeed?
                if( mysql_affected_rows($result) === 1 ) {
    
                    //Remove the old recovery-request
                    $sql = sprintf(
                        'DELETE FROM myRequests WHERE `token` = \'%s\'',
                        mysql_real_escape_string($token)
                    );
                    $result = mysql_query($sql);
    
                    //^We don't actually need to validate it, but you can if you want to
                    $message = 'Password updated. Go have fun!';
    
                } else {
    
                    $message = 'Could not update the password. Are you sure that the token is correct?';
    
                }
    
            } else {
    
                $message = 'Error in the SQL-query. Please try again.';
    
            }
        }
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <title>Password recovery</title>
            <style>
                form > * { display: block; }
            </style>
        </head>
        <body>
            <h1><?php echo $message; ?></h1>
            <?php if( $do_update_password ): ?>
    
                <form method="post">
                    <label for="token">Token:</label>
                    <input type="text" name="token" id="token" value="<?php echo $token; ?>" />
                    <label for="password1">Password:</label>
                    <input type="text" name="password[]" id="password1" />
                    <label for="password2">Password (again):</label>
                    <input type="text" name="password[]" id="password2" /> 
                    <input type="submit" name="update_pwd" value="Update your password!" />
                </form>
    
            <?php elseif($is_post_request && $token != ''): ?>
    
                <h2>Request that might've updated your password. Exciting!</h2>
    
            <?php else: ?>
    
                <form method="post">
                    <label for="email">E-mail address:</label>
                    <input type="text" name="email" id="email" />
                    <input type="submit" name="request_recovery" value="Request a new password" />
                </form>
    
            <?php endif; ?>
        </body>
    </html>
    

    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 myRequests

    CREATE TABLE IF NOT EXISTS `myRequests` (
      `request_id` int(6) NOT NULL AUTO_INCREMENT,
      `token` varchar(32) NOT NULL,
      `user_id` int(6) NOT NULL,
      `date` datetime NOT NULL,
      PRIMARY KEY (`request_id`),
      UNIQUE KEY `token` (`token`,`user_id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
    

    Good luck!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a method which writes into a database the username and password of
In the past I have stored database credentials (username, password) in another file (outside
At the moment, I have a database which contains username, password, etc. I am
I have the following criteria Database should be protected with a username and password.
I have the following database design: Employee Table: Username, Name, DivisionCode Division Table: SapCode,
I have the following database design: Employee Table: Username, Name Quiz Table: QuizID, Title,
So I have a mySQL database with a 'users' table which includes a username,
I have a windows form that takes username and password. It validates it with
In my database I have three tables: Users: UserID (Auto Numbering), UserName, UserPassword and
I managed to create the logic for the function but I have no idea

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.