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'];
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
<?php
session_start();
include_once ('connection.php');
if (isset($_POST['login'])){
$uemail = $_POST['email'];
$upassword = $_POST['password'];
}
$query = "SELECT * FROM users WHERE email = $uemail and password = $upassword";
$result = mysqli_query($connection, $query);
if(mysql_num_rows($query) == 1){
$_SESSION['email'] = $email;
header('Location: newfeeds.php');
exit();
}else{
while ($row = mysql_fetch_assoc($result)) {
echo $row["email"];
echo $row["password"];
}
}
?>
I have php manual it says stop using sql and replaced sqli but that didn't work. It throwing an errors.
Connected Successfully Fatal error: Call to undefined function
mysql_num_rows() in D:\XAMPP\htdocs\codeinventor\login.php on line 14
Change all the mysql_* functions to mysqli_* functions.
You can't use mysql and mysqli together. They are separate APIs and the resources they create are incompatible with one another. So Replace mysql_* with mysqli_* will help!
I agree with all here that you should change all the mysql_* functions to mysqli_* functions.
To your code with mysql API. Please use the following code:
<?php
session_start();
include_once ('connection.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($_POST['email'] != "" AND $_POST['password'] != ""){
$uemail = $_POST['email'];
$upassword = $_POST['password'];
$query = "SELECT * FROM users WHERE email = '$uemail' and password = '$upassword'";
$result = mysqli_query($connection, $query);
if(mysql_num_rows($query) == 1){
$_SESSION['email'] = $email;
header('Location: newfeeds.php');
exit();
}else{
while ($row = mysql_fetch_assoc($result)) {
echo $row["email"];
echo $row["password"];
}
}
}else{
echo "mail or password is not valid";
}
}else{
echo "The form has been not submitted";
}
?>
If one user has entered the following string as username:
' or uid like '%admin%
Your query will be like this:
$query = "SELECT * FROM users WHERE email = '' or uid like '%admin%' and password = '$upassword'";
That's why we told you you have to change all the mysql_* functions to mysqli_* functions.
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)
I send a password to php to get compared to the hash stored in the database.
my php is:
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
$query = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$passHash = mysql_result($query, 0);
if(password_verify($enteredPass, $passHash)){
echo "success";
}else{
echo "failure";
}
I also tried using mysqli_fetch_array() as well, but it still doesn't work. Does anyone know why this isn't working? thanks in advance to anyone who can help. (on a side note, $passHash returns null)
You are mixing two extensions, mysqli and mysql - mysqli_query and then mysql_result.
You are also open to SQL injection and should be sanitising your POST input before passing it directly to MySQL.
mysqli_query returns a result object and you then need to fetch the results from that object.
mysqli_fetch_row will return one row.
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
//...
$resultset = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$result = mysqli_fetch_row($resultset);
if(password_verify($enteredPass,$result[0])){
echo "success";
}else{
echo "failure";
}
I did solve my own problem with a simple while loop, i guess it will work fine, thanks everyone for your input:
$passHash = '';
while ($row = mysqli_fetch_array($query)) {
$passHash .= $row["passhash"];
}
Give this a try:
$enteredUser = mysqli_real_escape_string($con,$_POST["username"]);
$enteredPass = mysqli_real_escape_string($con,$_POST["password"]);
$sql = "SELECT * FROM `user` WHERE `username` = '$enteredUser'";
$result = $con->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($enteredPass, $row['passhash']))
{
echo "Success";
}
else {
echo "Sorry";
}
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.