I new to PHP and learning to update the user information in the mysql. The problem here is I am not able to display the data on the form nor able to update the user's information. My form seems to be empty instead of having any user information
<?php
session_start();
require('config.php');
error_reporting(0);
if(isset($_POST["submit"]))
{
$sqlupdate = mysql_query("UPDATE user
SET
first_Name = '{$_POST['sname']}',
password = '{$_POST['spassword']}',
WHERE first_Name = '{$_POST['sname']}'
");
}
$sql=mysql_query("SELECT * FROM student WHERE email='$_SESSION['SESS_USEREMAIL']' and password ='$_SESSION['SESS_USERPASS']' ");
while($record = mysql_fetch_array($sql)){
$first = $record['first_Name'];
$second = $record['first_Name'];
}
?>
<form method="post" name="studentform" id="student-form" action="#" enctype="multipart/form-data">
<div class="form-group">
<div class="inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
<input name="sname" id="studentname" placeholder="Name" class="form-control" type="text" value="<?php echo $first; ?>">
</div>
</div>
</div>
<div class="form-group">
<div class="inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input name="spassword" id="studentpassword" placeholder="Password" class="form-control" type="password" value="<?php echo $second; ?>">
</div>
</div>
</div>
<div class="form-group">
<button type="submit" id="ssubmitbtn" class="btn btn-primary btn-md" value="submit" name="submit">Submit<span class="glyphicon glyphicon-pencil "></button>
</div>
</form>
Assuming that your SQL is correct, you could use PDO's as followed;
<?php
$sFirst = '';
$sLast = '';
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM user WHERE email= :email and password = :password";
$st = $conn->prepare( $sql );
$st->bindValue(":email", $name, PDO::PARAM_STR);
$st->bindValue(":password", $password, PDO::PARAM_STR);
$st->execute();
if ( $row = $st->fetch() ){
$sFirst = $row['first_col_name'];
$sLast = $row['seccond_col_name'];
}
?>
You mention setting the values in the query from a session, using the following lines you can assign what ever var to be bound to the query;
$st->bindValue(":email", $_SESSION['SESS_USEREMAIL'], PDO::PARAM_STR);
$st->bindValue(":password", $_SESSION['SESS_USERPASS'], PDO::PARAM_STR);
And for your update you could use something like;
if(isset($_POST["submit"]))
{
$sError = '';
$sName = '';
$sPassword = '';
// basic error checking
if(isset($_POST['sname']) && $_POST['sname'] != ''){
$sName = $_POST['sname'];
}
if($sName == '') $sError .= "[MissingName]";
if(isset($_POST['spassword']) && $_POST['spassword'] != ''){
$sPassword = $_POST['spassword'];
}
if($sPassword == '') $sError .= "[MissingPassword]";
// if no errors, proceed to update
if($sError == ''){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE user first_name = :firstName, password = :password WHERE first_name :first_name";
$st = $conn->prepare( $sql );
$st->bindValue(":firstName", $_POST['sname'], PDO::PARAM_STR);
$st->bindValue(":password", $_POST['spassword'], PDO::PARAM_STR);
$st->execute();
}
}
Before updating I would check/validate the information entered is expected.
I would also use a Unique Identifier when updating to ensure the correct user is updated. For this I normally create a trigger on the table that will generate a short unique code.
$sql=mysqli_query("SELECT * FROM user WHERE email='$useremail' and password ='$userpassword' ");
$record = mysqli_fetch_array($sql);
instead write <?php echo $first... use <?php echo $redord['firstname] ;?>
This shoud solve your problem.
P.S
$useremail and $userpassword must stored in a session (in login page)
USE:
$_SESSION['usermail'] = $usermail;
$_SESSION['userpassword'] = $userpassword;
IN QUERY
$sql=mysql_query("SELECT * FROM user WHERE email='$useremail' and password ='$userpassword' ");
replace $usermail with $_SESSION['username']; and $userpassword with $_SESSION['userpassword'];
Related
I've been stuck on this issue for 3 days now. I'm trying to make a login form (I've already created a register form) and the database is working too. But now while I'm trying to make the login form, I've noticed that PHP only takes the last row from the database.
As you can clearly see in the first picture, my database has 3 records.
But when I try to log in on my account, it only lets me log in to the most recently created account, and not the others. Here's my current code:
<div class="login-form">
<form method="POST">
<p style="float:left;">
<input type="email" class="login-input" maxlength="40" name="login-email" id="login-email" placeholder="email" required><span style="color: red;"> *</span><br><br>
<input type="password" class="login-input" maxlength="32" name="login-passw" id="login-passw" placeholder="password" required><span style="color: red;"> *</span><br><br>
<input type="submit" class="btn" name="login-btn">
</p>
<?php
$email = $_POST["login-email"];
$passw = $_POST["login-passw"];
$encrypted_passw = md5($passw);
$sql = "SELECT id, email, passw FROM users";
$result = $db->query($sql);
// if (isset($_POST["login-btn"])) {
// if ($_POST["login-email"] == $result["email"]) {
// echo "<p>Logged in</p>";
// } else {
// echo "<p>wrong</p>";
// }
// }
while ($row = $result->fetch_assoc()) {
$get_email = $row["email"];
$get_usr = $row["username"];
$get_passw = $row["passw"];
}
if (isset($_POST["login-btn"])) {
if ($_POST["login-email"] == $get_email && $encrypted_passw == $get_passw) {
echo "<p>Logged in</p>";
} else {
echo "<p> wrong</p>";
}
}
?>
</form>
</div>
Try this. First of all I would place the php code above the HTML.
You only need to listen the post param login-btn. Read the other post data into vars and confirm its there before proceeding.
When you poll the DB you dont need to read every record (imagine you have thousands of records, you wouldn't want to pull them all down). Just filter for the supplied email with a where clause.
If the email exists it will return a result with the hashed password. Verify this matches and you are good to go.
The issue you're having where the last record in the db is beiung used is becuase in your loop, you are overwriting the var $get_email each time.
<?php
if (isset($_POST["login-btn"])) {
$email = (isset($_POST["login-email"]) ? $_POST["login-email"] : '');
$passw = (isset($_POST["login-passw"]) ? $_POST["login-passw"] : '');
if($email != "" && $passw != ""){
$encrypted_passw = md5($passw);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("SELECT email, passw FROM users where email = ?");
$stmt->bind_param($email);
$stmt->execute();
while ($row = $result->fetch_row()) {
$get_passw = $row["passw"];
if($encrypted_passw == $row['passw']){
echo "logged in";
}else{
echo 'no match';
}
}
}
}
?>
<div class="login-form">
<form method="POST">
<p style="float:left;">
<input type="email" class="login-input" maxlength="40" name="login-email" id="login-email" placeholder="email" required><span style="color: red;"> *</span><br><br>
<input type="password" class="login-input" maxlength="32" name="login-passw" id="login-passw" placeholder="password" required><span style="color: red;"> *</span><br><br>
<input type="submit" class="btn" name="login-btn">
</p>
</form>
</div>
Gottem! I was using array's instead of values
<?php
session_start();
include_once "../php/db_connect.php";
if (isset($_POST["login-btn"])) {
$email = $_POST["email"];
$passw = $_POST["passw"];
$encrypted = md5($passw);
$sql = "SELECT * FROM users WHERE email = '". $email ."'";
$result = $db->query($sql);
$get_result = $result->fetch_assoc();
if ($encrypted == $get_result["passw"]) {
echo "<p>Logged in!</p>";
$_SESSION["username"] = $get_result["username"];
$_SESSION["id"] = $get_result["id"];
$_SESSION["email"] = $get_result["email"];
Header("Location:../../../");
} else {
echo "<p>Error</p>";
}
}
?>
change your query to this
"SELECT id, email, passw FROM users where email='".$row["email"]."'
and password= '".$row["password"]."'"
you do not need to use foreach for all rows this query return only one row that you need
Statement
In login_check.php, it worked but I would like to change it into the prepared statement.
login.php
<body>
<div class="container">
<h1>Please Log In to the System</h1>
<form method="post" action="login_check.php">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<button type="submit" name="login" value="Log In">Log In</button>
</form>
</div>
</body>
login_check.php
<body>
<?php
//Establish connection
include 'connection.php';
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$sql = "SELECT * FROM admins WHERE admin_username = '".mysqli_real_escape_string($conn, $_POST['username'])."' and admin_password = '".mysqli_real_escape_string($conn, $_POST['password'])."'";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_array($query);
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if(!$result) //Username or Password is invalid!
{
?>
<div class="container">
<h1>Username or Password is invalid!</h1>
<form method="post" action="login.php">
<button type="submit">Back</button>
</form>
</div>
<?php
}
else //Username and Password are valid!
{
$_SESSION["admin_id"] = $result["admin_id"];
$_SESSION["admin_username"] = $result["admin_username"];
session_write_close();
header("location:front.php");
}
$conn->close();
?>
</body>
To change to prepared statements, you just need to
replace variables in your query with a ?
prepare the query
bind variables to the parameters
execute the statement
For your code that would look like this:
$sql = "SELECT * FROM admins WHERE admin_username = ? and admin_password = ?";
$stmt = $conn->prepare($sql) or die($conn->error);
$stmt->bind_value("ss", $_POST['username'], $_POST['password']);
$stmt->execute() or die($stmt->error);
$result = $stmt->get_result();
Note that you should not be storing passwords in plain text in your database. Please look into PHPs password_hash and password_verify functions to properly handle your passwords. You would use password_hash when storing the password in the database, and then your code for verifying the user would look something like:
$sql = "SELECT * FROM admins WHERE admin_username = ?";
$stmt = $conn->prepare($sql) or die($conn->error);
$stmt->bind_value("s", $_POST['username']);
$stmt->execute() or die($stmt->error);
$result = $stmt->get_result() or die($stmt->error);
$row = $result->fetch_array();
if (!$row|| !password_verify($_POST['password'], $row['admin_password']) {
// invalid username or password
login_check.php
<?php
//Establish connection
include 'connection.php';
$sql = "SELECT * FROM admins WHERE admin_username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array())
{
$hash = password_hash($_POST['password'],PASSWORD_DEFAULT);
mysqli_query($conn,"UPDATE admins SET admin_password = '$hash' WHERE admin_id='{$row['admin_id']}");
}
if(!$row || !password_verify($_POST['password'],$row['admin_password']))
{
?>
<div class="container">
<h1>Username or Password is invalid!</h1>
<form method="post" action="login.php">
<button style="font-size: 30px" type="submit" class="btn btn-dark"><b>Back</b> <i class="fas fa-arrow-alt-circle-left"></i></button>
</form>
</div>
<?php
}
else
{
$_SESSION["admin_id"] = $result["admin_id"];
$_SESSION["admin_username"] = $result["admin_username"];
session_write_close();
header("location:front.php");
}
$stmt->close();
$conn->close();
?>
</body>
There is no syntax error shown up but I think there are some mistakes in
=> mysqli_query($conn,"UPDATE admins SET admin_password = '$hash' WHERE admin_id ='{$row['admin_id']}");
=> if(!$row || !password_verify($_POST['password'],$row['admin_password']))
Form this code, the result is it always returns as username or password is invalid, even I put the valid ID and Password.
if(isset($_POST['btnLogin']))
{
$username = $_POST['txtusername'];
$pass_word = $_POST['txtpassword'];
$hashed_password = crypt(sha1($pass_word));
$sqlQuery = "SELECT * from users WHERE username = :username AND password = :password" ;
$statement = $conn->prepare($sqlQuery);
$statement->execute(array(':username' =>$user , ':password'=>$hashed_password));
while($row->$statement->fetch())
{
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
if(strcmp('$password', '$hashed_password') == 0)
{
echo "<script type='text/javascript'>console.log("Sucess");</script>";
}
else
{
echo "<script type='text/javascript'>console.log("Failed");</script>";
}
}
}
In here I am implementing the Sign in a page using PHP PDO codes.
I have no previous experience in using PHP PDO.I do the Sign up page without any errors but unfortunately program is not execute after
while($row->$statement->fetch())
here are the HTML codes
<section>
<div class="container">
<div class="login-form">
<h1>Sign In</h1>
<form id="login-form" method="post" action="">
<div class="form-group">
<input type="text" name="txtusername" placeholder="Username" data-validation="required">
</div>
<div>
<input type="password" name="txtpassword" placeholder="Password" data-validation="required">
</div>
<input type="submit" name="btnLogin" value="Login">
</form>
</div>
</div>
</section>
PHP VERSION : 5.3.8
Please give any suggestion to me for solve it
Try the below. If it doesn't work, wrap your query in this and turn error reporting on.
if(isset($_POST['btnLogin']))
{
$username = $_POST['txtusername'];
$pass_word = $_POST['txtpassword'];
$hashed_password = crypt(sha1($pass_word));
$sqlQuery = "SELECT * from users WHERE username = :username AND password = :password" ;
$statement = $conn->prepare($sqlQuery);
$statement->execute(array(':username' =>$user , ':password'=>$hashed_password));
while($row = $statement->fetch_object())
{
$id = $row->id;
$username = $row->username;
$password = $row->password;
if(strcmp('$password', '$hashed_password') == 0)
{
echo '<script type="text/javascript">console.log("Success");</script>';
}
else
{
echo '<script type="text/javascript">console.log("Failed");</script>';
}
}
}
I wanted to make a multi user login. At least 2 type of users that is admin and a user. When I tried to enter the username and password as an admin, got the error displayed as 'Username and Password Invalid' instead. Same for user.
PHP
include_once 'config.php';
$error="";
if(isset($_POST['login'])){
if(empty($_POST['username']) || empty($_POST['password'])){
$error = '<div class="alert alert-danger">Username or Password is Invalid</div>';
} else {
$username= $_POST['username'];
$password= $_POST['password'];
$stmt = $con->prepare("SELECT * FROM users WHERE username=? AND password=? ");
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$row = $stmt->fetch();
$user = $row['username'];
$pass = $row['password'];
$id = $row['id'];
$type = $row['typeuser'];
if ($username==$user && $pass==$password){
session_start();
$_SESSION['username']=$user;
$_SESSION['passsword']=$pass;
$_SESSION['id']=$id;
$_SESSION['typeuser']=$type;
if($type=='admin'){
header("Location: dashboard.php");
} else if ($type=='user'){
header("Location: user_dashboard.php");
}
} else
{
$error = "Username or Password is Invalid";
}
}
mysqli_close($con); // Closing connection
}
?>
FORM
<form role="form" method="post" action="" >
<div class="page-content container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-wrapper">
<div class="box">
<div class="content-wrap">
<h6>Sign In</h6>
<input class="form-control" type="text" placeholder="Username" id="username" name="username"><br/>
<input class="form-control" type="password" placeholder="Password" id="password" name="password"><br/>
<input class="btn btn-primary btn-lg" type="submit" value="Login" name="login"><br><br>
<strong class = "text-danger"><?php echo $error; ?></strong>
</div>
</div>
<div class="already">
<p>Don't have an account yet?</p>
Sign Up
</div>
</div>
</div>
</div>
</div>
</form>
I don't know why this error is displayed since I did the code right.
mysqli execute and fetch is not same as pdo when you use
execute in mysqli you need to use fetch with bind_result. Try follwoing code/ change your
$stmt = $con->prepare("SELECT * FROM users WHERE username=? AND password=? ");
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$row = $stmt->fetch();
$user = $row['username'];
$pass = $row['password'];
$id = $row['id'];
$type = $row['typeuser'];
To
$stmt = $con->prepare("SELECT username,password,id,typeuser FROM users WHERE username=? AND password=? ");
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$stmt->bind_result($user, $pass,$id,$type);
$stmt->fetch();
I'm still fairly new to the prepared statements because it was brought to my attention by another user. I've been able to create a registration function that properly prepares the statement, binds it and then executes it. It goes into the database just fine. However, I'm not sure I understand how the login part would work. I'm trying to fetch a row and the result I keep getting is "1" but not the row + data inside the row. Any advice?
Database:
login.php (where the form is located)
<form id="loginform" class="form-horizontal" role="form" action="" method="post">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="Lusername" placeholder="Username or Email">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="Lpassword" placeholder="Password">
</div>
<div class="input-group">
<div class="checkbox">
<label>
<input id="login-remember" type="checkbox" name="remember" value="1"> Remember me
</label>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button id="btn-login" type="submit" class="btn btn-success"><i class="icon-hand-right"></i>Submit</button>
</div>
</div>
</form>
script:
<script type="text/javascript">
$(function() {
$("#loginform").bind('submit',function() {
var username = $('#login-username').val();
var password = $('#login-password').val();
$.post('scripts/loginFunction.php',{username:username, password:password}, function(data){
$('#signupsuccess').show();
}).fail(function(){{
$('#signupalert').show();
}});
return false;
});
});
</script>
loginFunction.php
<?php
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT `Username`, `Password` FROM `users` WHERE `Username` = ?");
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
/*if($stmt->num_rows == 1){
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
// here is where you could verify the password
if(password_verify($password, $row['Password'])) {
// good password
echo 'all good!';
}
} else {
//echo "failed to find row";
}*/
?>
loginFunction.php that does work and queries the database properly
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($query);
if($result->num_rows == 1){
$row = mysqli_fetch_array($result);
if(password_verify($password, $row['Password'])){
echo "Login successful!";
}
else{
echo "Login failed.";
}
}
EDIT: Here is the code you should use. Note how $stmt is carried throughout:
$stmt = $conn->prepare("SELECT `Username`, `Password` FROM `users` WHERE `Username` = ?");
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
/*if($stmt->num_rows == 1){
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
// here is where you could verify the password
if(password_verify($password, $row['Password'])) {
// good password
echo 'all good!';
}
} else {
//echo "failed to find row";
}*/
I have resolved the issue. When I went to fetch, I needed to store it in a separate variable than the one that the user is storing their entered password into. This can be reflected in the code below:
<?php
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
$dbusername = ""; //These two being the new variables
$dbpassword = "";
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT Username, Password FROM users WHERE Username = ?;");
$stmt->bind_param('s', $username);
$stmt->execute();
if($stmt->execute() == true){
$stmt->bind_result($dbusername, $dbpassword);
$stmt->fetch();
if(password_verify($password, $dbpassword)) {
echo 'successful';
}
else{
echo 'failed';
}
}
else{
echo 'failed';
}
?>