How to retrive only one cell from MySQL table with PHP - php

I'm trying to create a forgotten password form that emails users their password. I'm having a problem, though, with the actual password part. You see, I have the email and comparing the email correct, except whenever I send the email I always get either "Your password is ." or "Your password is Array". I'm using:
$check_email = mysql_num_rows(mysql_query("SELECT email FROM userRecovery WHERE email = '$to'"));
if($check_email == 1){
$qtip = mysql_query("SELECT password FROM userRecovery WHERE email = '$to'");
$theirPassword = mysql_fetch_array($qtip);
Rest of the Code...
}
I used to be able to do this correctly, but I haven't done PHP or MySQL in too long so it's slightly annoying (that, and I'm at a beginner-intermediate kind of level). I remember having this exact problem, but I don't have the code with me to find out what I did. If you think I left out a detail, please say so.
Any help if appreciated.

$theirPassword, as you're using it, is an array (as what's being fetched via your mysql_fetch_array command). Try either $theirPassword['password'] or use just `mysql_result($qtip,'password')``

mysql_fetch_array returns an array, so if you're using your $theirPassword it will contain an array. Since you're selecting password from your query, you likely need:
$qtip = mysql_query("SELECT password FROM userRecovery WHERE email = '$to'");
$row = mysql_fetch_array($qtip);
$theirPassword = $row['password'];

What about fetching the email address and the password in one query? SELECT email,password FROM userRecovery WHERE email = '$to'. Then you can get the password just like in the previous 2 answers ($theirPassword['password']).
On top of that you may find this blog post about storing passwords in a db useful - http://blog.moertel.com/articles/2006/12/15/never-store-passwords-in-a-database

$sql = "SELECT password FROM userRecovery WHERE email = '$to'";
$password = mysql_result(mysql_query($sql), 0);

Related

sending an email based on data from MySQL table

I've got email function setup and working by setting the code to email a specific email address. However, with this is that it goes to the same email address everytime the submit button is pressed based on the data entered in a text box who the mail comes from.
However, I want to change it so that when a user enters their username in the username box it checks my database table for that username and checks their email address and emails them all the information set for that user.
The code i'm using is ;
$username = $_POST['username'];
$my_query="SELECT * from loanusers where username = '$username'";
$result= mysqli_query($connection, $my_query);
$to = $myrow["emailaddess"];
$subject = 'CSG - Forgotten Password';
$sender = 'CSGLoanSystem#mail.com';
$password = $myrow["password"];
$admin = 'CSGLoanSystem Admin Team';
$body = <<< EMAIL
Hi {$username}, You have recently requested a notification of your password.
The Password registered with account {$username} is $password.
Thanks - {$admin}
EMAIL;
$header = "From:" . $sender;
if ($result):
mail($to, $subject, $body, $header);
$feedback = 'Email Sent';
endif;
At the moment when the submit button is pressed, the page refreshes but nothing actually happens and no email is received at the expected email address?
Pointing to the right direction:
Read up on MySQL and PDO. Also Read up on prepared statements and parameter binding.
Elaborating on the directions given:
There are many ways to connect to a database, and there are many different databases available. One popular database software is called MySQL, and the coding method that is most recommended to connect to that database is PDO for reasons such as having better methods for preventing security breaches.
You can find a lot of online tutorials on how to connect to a database, so I won't go into that, though I will however give you an example of a query you could use to do your email searching, and also I'll include prepared statements and parameter binding since these two details are often misunderstood by a lot of programmers.
If you have the following table:
users
______________________________
| username | email |
|------------+-----------------|
| john44 | abc#gmail.com |
|------------+-----------------|
| adam11 | 123#gmail.com |
|------------+-----------------|
the following code would allow you to retrieve john44's email:
$username = $_POST['username'];//getting the username written in the form
$sql = "SELECT email FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//here I'm just outputting the obtained email for you to see
//it works, however you would then use the email saved in
//$result['email'] whichever way you want.
echo "email = {$result['email']}<br>";
Edited:
After you edited your code, I noticed you are not fetching the information you queried. Insert the following code after line $result= mysqli_query($connection, $my_query);:
$myrow = mysqli_fetch_assoc($result);

Comparing mysql password hashes using query row returning 0 (not working)

I am creating a login system for my website using a mysql database.
When the user registers, it saves the password to the database using:
$password = hash("sha512","somesalt".$password."moresalt");
Then when I login, I compare the password entered to the password in the database using the same hash function.
To compare the database I use this:
$query = mysql_query("select * from users where password='$password' AND email='$email'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {//do login stuff}
But rows always returns 0. When I remove the hash function from both the register and login, it logs in fine. What's wrong?
As a side note in case anyone's wondering, I would be using mysqli but my webhosting's database version is old. They are using 5.2 I believe.
I forgot to mention that I did check to make sure the database did match what it was getting as seen in these pics (can't embed pics so links):
https://drive.google.com/file/d/0B_u6weYp5wTCQng5eVhTSkZFRDg/view?usp=sharing
https://drive.google.com/file/d/0B_u6weYp5wTCQVRXTkNqdzhWUFE/view?usp=sharing
what is the length of your password field in database???
The reason seems to me is the hashed password length is too long and while saving to database part or it is dropped...
Then when you compare you get 0 rows...
Okay, I would like to suggest that you use prepared statements other than the mysql library. It is much more secure and reliable.
$query = "SELECT * FROM `users` WHERE AND `email`=:email_token";
Then you prepare and execute your query
$data = $connection->prepare($query);
try {
$data->bindParam(":email_token",$_POST["email"],PDO::PARAM_STR);
$data->execute();
}
$result = $data->fetch(PDO::FETCH_ASSOC);
while($row = $result) {
$out = $row["password"];
}
if($out == $_POST["password"]) {
//loggin
} else {
//get lost
}
This is a very basic structure but essentially you want to pull the password out of the database first then compare the strings instead of doing it all with your query.

MySQL multiple queries not working

Problem has been solved
I have created a form that processes the changing of user information from the admin side e.g. the admin changes a user's username and/or email. I am having trouble processing multiple queries.
For example, if the admin changes the username, the query works. If the admin changes the email address, the query works. But if the admin changes the username and email at the same time through the form then only the username changes.
Any ideas? I will submit my code but I will change variables for security reasons etc. Also, anything in capitals has been changed for security reasons. The code is all correct for each individual function because as I said, if I ONLY change the email, it works and actually changes. But if I change the username AND email, only the username will change despite the fact the email query runs and it echo's the email has been changed!
Also, it is worth noting that all of the fields e.g. username field and email field are part of one form that submits to one page.
if (isset($_POST['SUBMIT_BUTTON_PRESSED'])) {
//Gather all inputs from the form and sanitise it.
//REMOVED FOR SECURITY REASONS.
if($USERNAME_NEW != "") {
if($USERNAME_NEW == $CURRENT_USERNAME) {
echo "You have entered the username you are already using. Please enter a different username.";
} else {
$CHECK_USERNAME = "SELECT USERNAME_ROW FROM USERS_TABLE WHERE username='$USERNAME_NEW'";
$RUN_QUERY = mysqli_query($CONNECTION INFO, $CHECK_USERNAME);
$RESULT = mysqli_num_rows($RUN_QUERY);
if($RESULT > 0) {
echo "That username already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_username = true;
$USERNAME = $NEW_USERNAME; //NOT NEEDED BUT IT STILL WORKS
$THE_SQL_QUERY = "UPDATE USER_TABLE SET username='$USERNAME' WHERE username='$ORIGINAL USERNAME'";
$RUN_THIS_QUERY= mysqli_query($CONNECTION INFO, $THE_SQL_QUERY);
echo "The user's username has been changed to: ". $USERNAME;
}
}
}
if($EMAIL != "") {
if($EMAIL == $CURRENT_EMAIL) {
echo "You have entered the same email address to the one you are already using. Please enter a different email address.";
} else {
$CHECK_EMAIL = "SELECT USERS_EMAIL FROM USER_TABLE WHERE username='$USER'";
$CHECK_EMAIL_QUERY = mysqli_query($CONNECTION_INFO, $CHECK_EMAIL);
$RESULT = mysqli_num_rows($CHECK_EMAIL_QUERY);
if($RESULT > 0) {
echo "That email already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_email = true;
$THE_NEW_EMAIL = $FINAL_EMAIL_THING; // AGAIN NOT NEEDED BUT STILL WORKS
$THE_SQL= "UPDATE USER_TABLE SET USER_EMAIL='$EMAIL' WHERE username='$USER' LIMIT 1"; // REMOVED THE LIMIT 1, STILL DOESN'T WORK
$RUN_THIS_QUERY = mysqli_query($CONNECTION, $THE_SQL);
if($RUN_THIS_QUERY) {
echo "The user's email has been changed."; // EVEN WHEN BOTH FIELDS ARE SUBMITTED THIS WORKS SO THE QUERY IS RUNNING BUT THE EMAIL DOESN'T CHANGE
}
}
}
}
Thanks for the help! Also, no un-witty remarks about how my question is structured etc. because I don't care to be honest. I just want this code working to be honest because I've been working on it for a while. This may be something simple or I might be using the wrong approach for this type of form submission.
Remember: THIS CODE DOES WORK WHEN I SUBMIT EACH FIELD SEPARATELY!
Its very hard to figure out as you are not producing the real code.
I think you have missed something here.
As you are using USER_NAME as key in the SQL's, make sure that you are using the updated username in the second sets of SQL (to update the email) as they are already replaced by the first SQL.
And there is no security risk while showing your codes snippets to someone else. Hide only the username/passwords or Identities. :)

How to improve login script?

How can I ensure my login script is secure and make it better, This is my first code:
Help is most appreciated.
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, lastname, email, mobile, username, password)
VALUES('$firstname', '$lastname','$email', '$mobile','$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
header("Location: /registration?registration=true");
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
Follow Artefacto's advice about SQL injection and Hashing passwords in the database. Other things ...
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
Wont work because you can't echo then send a header. Headers must be sent before any output.
Also, there is no point doing this:
header("Location: /registration?registration=false");
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
The webbrowser will redirect straight away and the user won't see the handy message you've printed.
Also, it's usual to ask for 2 password fields on registration forms incase the user made a typo and didn't notice because all the text was *'s. You compare the 2 and if they are different you assume a typo was made and ask again.
That's not a login script. It's a registration script.
See SQL injection in the PHP manual. Your program is vulnerable to this kind of attacks.
Also, don't just or die(mysql_error()). This will expose information about your database that you may not want to expose (table names, etc.). Use proper error handling. For instance, you can throw an exception and define a uncaught exception handler that shows a "oops" page and logs the error.
Finally, use hashes strong than MD5, such as sha1.
As said by #Artefacto, that's not a login script.
But if you intend to do a login script I would like to give you a suggestion. I've done this a while ago.
Instead of doing something like this:
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
I would do this:
$sql = "SELECT * FROM users WHERE username = '$username'";
$user = //use the php-sql (query, fetch_row) commands to fetch the user row.
if (strcmp($user['password'], $password) == 0) {
//log in success
}
By doing this, you avoid SQL Injection in a simple and elegant way. What you guys think about it?
To reiterate what everyone else mentioned. It's important to protect yourself (and sever) from SQL injection. For example:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
You're just simple taking the value from $_POST['username'] and placing it in the variable $username.
Some people aren't very nice and will try to break your program :( So it's always recommended to escape any data that was taken from a user, before placing it into an SQL query.
For instance...
This:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
Becomes:
$checkuser = mysql_query("SELECT username FROM users WHERE username='" .mysql_real_escape_string($username). "'");

Password reset script only fires half the time

I had an inefficient piece of code for resetting passwords based on a user entering either their username or their email address. The PHP script branched depending on the identifier used. I collapsed it into one which now works if the user enters their username but not if they enter their email address. Here is the salient code:
$identifier = isset($_POST["username"])?"username":"email";
$ident = isset($_POST["username"])?trim(mysqli_real_escape_string($mysqli,(check_chars_username($_POST["username"])))):trim(mysqli_real_escape_string($mysqli, (check_chars_email($_POST["email"]))));
//create and issue the query
$sql = "SELECT * FROM aromaMaster WHERE $identifier = '$ident'";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if(mysqli_num_rows($sql_res) == 0) {
//wrong login info
header("Location: password_reset_form.html/error=$ident");
exit();
}
$info = mysqli_fetch_array($sql_res);
$userid = $info["id"];
$username = stripslashes($info["username"]);
$email = stripslashes($info["email"]);
I have checked and doubled checked that the email form field is called email and it is. It's got me scratching my head. Particularly interesting is the header redirect. When I enter an email address and am redirected, the variable $ident appears empty.
As you've noted in your comment, you have to check for the username variable of the $_POST array to be empty.
It's also a good idea to check if the variable is even there in the first place in addition to and before you test against it being blank.
$identifier =
(isset($_POST["username"]) && !empty($_POST["username"])) ? "username":"email";
When you're sending your form across, all of the text input fields will come through, even if they're blank. Blank is not the same as empty. That's the reason the first part of the ternary operator is always true in your initial code.

Categories