I want to echo a field from database IF two other fields that are entered are correct with their corresponding ones in the database.
example
Email: (enters email: (is it same as one in database))
Answer: (enters answer: (is it the same as one matching email in database?))
Code Echos.... Your password is here: (**********).
No matter the input on my code though, it always returns message ' Security Answer Correct' but then does not echo the variable.
PhP Code
$query = mysqli_query ($db, "SELECT * FROM admin where email = '$email' AND securitya = '$securitya'");
$password = mysqli_query ($db, "SELECT password FROM admin WHERE email = '$email' AND securitya = '$securitya'");
$passwordrow= mysqli_fetch_array ($password);
$result_password = $passwordrow ['password'];
$row = mysqli_fetch_array ($query);
if($row['email'] = $email AND $row['securitya'] = $securitya)
{
$_SESSION['email'] = $row['securitya'];
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Security Answer Correct');
</SCRIPT>");
echo ('<br>Password: ' . $result_password . '<br>');
}
else
{
die ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Incorrect Security Answer, Please Try Again')
window.location.href='passwordreset.php';
</SCRIPT>");
}
}
And I receive the error message:
Notice: Undefined variable: result_password in C:\xampp\htdocs\Intranet\passwordreset.php on line 118
What is Wrong with my statements is the question I am trying to ask.
Can anyone help?
Try with this code, I think this happens due to multiple query with same object.
$query = mysqli_query ($db, "SELECT * FROM admin where email = '$email' AND securitya = '$securitya'");
$row = mysqli_fetch_array ($query);
if($row['email'] == $email AND $row['securitya'] == $securitya)
{
$_SESSION['email'] = $row['securitya'];
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Security Answer Correct');
</SCRIPT>");
echo ('<br>Password: ' . $row['password'] . '<br>');
}
else
{
die ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Incorrect Security Answer, Please Try Again')
window.location.href='passwordreset.php';
</SCRIPT>");
}
}
You are setting the values in the line below (which is triggering a false positive for the if), instead of comparing them.
if($row['email'] = $email AND $row['securitya'] = $securitya)
Use == to compare:
if($row['email'] == $email AND $row['securitya'] == $securitya)
Your query might be failing, use the debugging functions available, add or die(mysqli_error($db)); after your queries to see if they're failing or not.
Edit 1
Seeing as you are using MySQLi you should use prepared statements to prevent SQL injections.
Edit 2
You are assigning values instead of comparing values, use == not = in your if statements.
Edit 3
Never trust user input, you should always sanitize all your input. Check out htmlspecialchars, intval, trim (not sanitizing but can be used to check for empty fields).
You have an extra space as typo.
Replace this $result_password = $passwordrow ['password'];
with this
$result_password = $passwordrow['password'];
Replace
if($row['email'] = $email AND $row['securitya'] = $securitya)
with
if($row['email'] == $email && $row['securitya'] == $securitya)
Related
I'm performing a query to check if a user exists before adding it to the database. If that result comes back then die and echo 'username already exists' but if it comes back empty then add the new user to the database.
For some reason it just adds a new user to the database anyway.
//If post was
if (isset($_POST['submit'])) {
// Check if username is blank
if (!isset($_POST['username']) || empty($_POST['username'])) {
echo "Username was blank<br />";
die();
} else {
$username = mysqli_real_escape_string($connection, $_POST['username']);
}
// Check if password is blank
if (!isset($_POST['password']) || empty($_POST['password'])) {
echo "Password was blank<br />";
die();
} else {
$password = mysqli_real_escape_string($connection, $_POST['password']);
$password2 = md5($password);
//echo $password;
}
// Check if email is blank
if (!isset($_POST['email']) || empty($_POST['email'])) {
echo "Email was blank<br />";
die();
} else {
$email = mysqli_real_escape_string($connection, $_POST['email']);
//$password = md5($password);
//echo $password;
}
//Check to see if username alread exsists
$query_check = "SELECT * FROM users WHERE user = '$username' LIMIT 1";
$result_check = mysqli_query($connection, $query_check);
if(count(mysqli_fetch_array($result_check)) === 1) {
echo "Username exists.";
die();
} else {
$query = "INSERT INTO users (user, pass, email) VALUES ('$username','$password2','$email');";
$result = mysqli_query($connection, $query);
if($result){ // returned TRUE, e.g. in case of a DELETE sql
$_SESSION["username"] = $username;
header("Location: ../profile.php");
} else { // returned FALSE
//echo "Error: " . mysqli_error($connection);
echo "Error during register <a href='../register.php'>Back To Register</a>";
die();
}
}
} else {
header("Location: ../index.php");
}
After taking a few minutes testing your code, found that you're using the wrong function.
mysqli_fetch_array():
Fetch a result row as an associative, a numeric array, or both
You're trying to fetch an associative array.
As opposed to mysqli_num_rows():
Gets the number of rows in a result
Replace (and which seems to have been taken from FĂ©lix's answer)
if(count(mysqli_fetch_array($result_check)) === 1)
with
if(mysqli_num_rows($result_check) == 1)
or
if(mysqli_num_rows($result_check) > 0)
Your original post contained:
if(mysqli_fetch_array($result_check) === 1)
which still stands to be the wrong method.
I even said to use mysqli_num_rows() in a comment, but nothing was said about it:
if(mysqli_num_rows($result_check) >0) and make sure $username is defined. We don't know how/where if it is even defined.
Now, if THAT fails, then your form element isn't named, and/or something else in your form is failing you.
I.e.: <input type="text" name="username">
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Regarding using MD5.
That isn't considered safe to use anymore, as far as password hashing goes.
That technology is old and is considered broken.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Pulled from ircmaxell's answer which uses PDO with prepared statements and password_hash():
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
Footnotes:
I noticed you are using headers.
You should add exit; after each header. Otherwise, your code may want to continue executing.
header("Location: ../profile.php");
exit;
and do the same for the other one also.
You're also using sessions. session_start(); isn't present in your posted and will fail if it isn't included; an insight.
here
if(mysqli_fetch_array($result_check) === 1) {
the value returned by mysqli_fetch_array won't be an integer but an array. You seem to want to count it:
if(count(mysqli_fetch_array($result_check)) === 1) {
In the case somehow two users would have been inserted for whatever reason, checking if count is greater than 0 may prevent a third one being inserted:
if(count(mysqli_fetch_array($result_check)) > 0) {
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is my attempt at a basic mysqli php login script (im only learning, so please dont be too harsh).
Can anyone see why it would be bringing up 0 rows every time and failing to login?
<?php
$con = mysqli_connect("localhost","user","pass","database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL, Please contact an Administrator";
}
$username = mysqli_real_escape_string($_POST['username']);
$password = mysqli_real_escape_string($_POST['password']);
$query = "SELECT * FROM users WHERE user_name='$username' AND pass_phrase='$password'";
$result = mysqli_query($con, $query);
$row_cnt = mysqli_num_rows($result);
if (!$row_cnt == 0) {
echo "Usename/Password Combination Failed";
} else {
echo "Welcome " . $_POST['username'];
}
mysqli_close($con);
?>
You need to pass DB connection to mysqli_real_escape_string() as an added parameter.
What you're presently using:
$username = mysqli_real_escape_string($_POST['username']);
$password = mysqli_real_escape_string($_POST['password']);
What you should be using:
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
Plus, if if (!$row_cnt == 0) doesn't work after making those changes, try a reverse approach:
I.e.:
$row_cnt = mysqli_num_rows($result);
if ($row_cnt > 0) {
echo "Welcome " . $_POST['username'];
} else {
echo "Usename/Password Combination Failed";
}
Consider adding or die(mysqli_error($con)) to mysqli_query() to signal errors in code.
Sidenote:
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommed you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Footnotes:
Consider looking into using:
Prepared statements, or PDO with prepared statements, they're much safer.
Try removing ! or == 0 from your if condition at the bottom. Or even better:
if ($row_cnt) {
// Welcome
} else {
// Notify about authentication failure
}
Also, it's a good practice to hash your password/pass phrase.
This is very basic approach for login, assuming you have user table with id, username, and password :
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$errors = array();
if(!$_POST['username']) //check if username has been filled
{
$errors[] = 'bla bla text for empty username notice';
}
else
{
$username = mysqli_real_escape_string($conn, trim($_POST['username']));
}
if(!$_POST['password'])//check if password has been filled
{
$errors[] = 'bla bla text for empty password notice';
}
else
{
$password = mysqli_real_escape_string($conn, trim($_POST['username']));
}
if(empty($errors)) //no errors appears
{
$query = "SELECT * FROM tablename WHERE user_name = '$username' AND password = SHA1('$password')";
$result = #mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1)
{
//if one database row (record) matches the input:
// Start the session, fetch the record and insert the three values in an array
session_start();
$_SESSION = mysqli_fetch_array($result, MYSQLI_ASSOC);
header("direct to after login page");
}
else
{
// No match was made
$errors[] = 'Sorry no record match with the data you have submitted';
}
}
else
{
// If there was a problem.
echo mysqli_connect_error($conn);
}
}
You need to fix the quoting in your query. Right now you are trying to login as a user with user name $username and password $password and most likely no such combination exists. Also unless you are allowing two users to have the same username you should just query based on the username and then compare the hashed password provided with the stored hashed password.
I am trying to return a username when a user forgets their username. I have it validating again their email address but for some reason it just keeps saying 'Error: cannot find username'. I am using the correct mysqli syntax I hope.
if (isset($_POST['user'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$username = "";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
$errmsg = 'Error: ' . $email . ' is not a valid email address';
} else {
$query = "SELECT email FROM admin WHERE email = '$email'";
$results = mysqli_query($con, $query);
$query2 = mysqli_fetch_array($results);
if ($query2 == 0) {
$errmsg = 'Error: ' . $email . ' is not found, please try again';
}
if (!errmsg) {
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con, $getuname)) {
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: ' . $row['username'] . '</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
}
I am a noob when it comes to this but am pretty sure this is correct. if not where did i go wrong?
These are some of the errors I noticed:
You're doing if (!errmsg) but there's no such constant and you want if (!$errmsg) instead.
As Marc B pointed out, you're doing $row = mysql_fetch_array($getuname); but you want $row = mysqli_fetch_array($getuname); instead.
Also, the specific problem you're describing is probably because of the $username declaration just before the mysqli_close statement. You're resetting the value of $username there and it'd always echo out the same message regardless of the result of your database query.
$username = "";
if(condition)
{
# code ...
}
else
{
# code ...
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
That's one of the many logical mistakes in your code. Structure the if-else blocks with proper indentation and you shouldn't have this issue.
I found some mistake in your code, you can see the mistake in Mark B and Amal Murali's answer. Let me make your else block simple and more clear. you can use only 1 query instead of 2 queries.
else {
$query = mysqli_query("SELECT * FROM admin WHERE email = '$email'");
$row = mysqli_fetch_array($query);
$numrows = mysqli_num_rows($query);
if (!$errmsg){
if($numrows == 0) {
$errmsg = 'Error: '.$email.' is not found, please try again';
// or here you can add message like Cannot find username
}
else
{
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
}
Your code is a disaster. You're using ereg, which has been deprecated since the stone age. You're mixing calls to the mysql (no i) and the mysqli (with i) libraries. They are NOT interchangeable and are NOT compatible with each other.
You need to switch over to the preg functions, and standardize on a SINGLE mysql library. Since mysql is deprecated as well, use mysqli ONLY.
$row = mysql_fetch_array($getuname);
^^^---note the LACK of an i
if (!errmsg){
^^^--note the lack of a $ sign, meaning this is undefined/undeclared constant.
Change this section of code:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con,$getuname))
{
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
to:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
$uresult = mysqli_query($con, $getuname);
if (!$uresult))
{
die('Error: ' . mysqli_error($con));
}
$row = mysqli_fetch_array($uresult);
if ($row) {
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
} else {
$username = '<div class="registererror">Error: cannot find username</div>';
}
}
Your mistakes:
You were calling mysql_fetch_array instead of mysqli_fetch_array.
You were passing the SQL string to mysql_fetch_array, not the result of mysqli_query.
You weren't checking whether a row was returned, you were just setting $username unconditionally -- first to the success message, then to the failure message.
Hi guys i've been working for straight 12 hours, i can't seem to find fix.
i'm trying to compare user-input to database result for example $username == $result echo "Username is aldready taken, but the problem is it's passing through 2 statements without a break, and if i put a break to exit the loop, it always check for $email == $result2 despite of not entering any email in the field.
if (isset($_POST['username']) or isset($_POST['email'])) {
$extract = mysql_query("
SELECT
`username`, `email`
FROM `users`
WHERE `username`='$username' OR `email`='$email'
");
$resultq = mysql_num_rows($extract);
while ($row = mysql_fetch_array($extract)) {
$result = $row['username'];
$result2 = $row['email'];
echo " " . $result;
echo " " . $result2;
if ($username == $result) {
echo " Username is already Taken!";
// break; //whenever i put break, it always gives me the else if statement echo, despite not entering any email in the field
} //$pass = $_POST['pass'];
else if ($email == $result2) {
echo "Email Address is already used!";
// break;
} else {
}
}
}
Upgrade from mysql to either MySQLi, or PDO.
However;
$extract= mysql_query("SELECT username, email FROM users where username='$username' or email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0) {
echo 'Either your username, or email is already taken!';
return;
}
See sniko for the answer to your initial problem. However, see the following...
You're not defining $username or $email
if ($username == $result ) should be
if ($_POST['username'] == $result )
or you could define $username and $email at the beginning of the conditional.
You should also change this:
isset($_POST['username']) or isset($_POST['email'])
to this:
isset($_POST['username']) && isset($_POST['email'])
because you depend on both in your query.
and as sniko said, switch to mysqli or PDO. mysql_ is deprecated.
full sample:
if(isset($_POST['username']) && isset($_POST['email']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$extract= mysql_query("SELECT username, email FROM users where username='$username' or email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0) {
echo 'Either your username, or email is already taken!';
return;
}
}
Also note, you're not sanitizing the input. You could be hacked with this input. switching to mysqli or pdo and using prepared statements would help this.
I have written a PHP script that I use for authentication with e-mail and password since e-mail is identified as unique.
I want to echo "true" as well as echo :: fname (First Name). how can I write it? Following is my PHP code.
include "db_config.php";
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "select fname,e_mail,password from user where e_mail = '$email' and pwd = '$password' ";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0){
echo "true";
}
else{
echo "Login Failed";
}
If you can suggest me some better way to write this code, please let me know.
Consider the comments about mysql_* and mysql_real_escape_string, but after you get your result, you echo it like this, adapted from the manual:
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$row = mysql_fetch_assoc($result);
echo "true" . $row['fname'];
if (mysql_num_rows($result) > 0)
{
echo mysql_result($result, 0);
}
-- or --
The code from Sankalp's or GDP's answers. (mysql_fetch_array)
mysql_result is not good if you want to display many results, it's good for just a few of them.
BTW, I'd like to point you to some omissions in your code:
you should check if every $_POST or $_GET variables are set by using isset or empty.
your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.
Example of checking if variables are set:
Using isset():
if(isset($_POST['email'])) $email = $_POST['email'];
if(isset($_POST['password'])) $password = $_POST['password'];
Using empty():
if(!empty($_POST['email'])) $email = $_POST['email'];
if(!empty($_POST['password'])) $password = $_POST['password'];
$row = mysql_fetch_array($result, MYSQL_NUM)
echo $row[0]; //fname
echo $row[1]; //email
or you can use MYSQL_ASSOC to get a named array and access values as
echo $row['fname'];