Form fails to proceed on submit - php

I have a login form(index.php) which allows students to access their portal, the students' registration number and password is then checked if inserted(login.php) and proceeds to a class(StudentLogin.php) which will then allow the students access their portal if at all the credentials match with the ones in the database. On entering the correct credentials, the process doesn't proceed to the stud_page.php.....I would appreciate any help on this cause i don't understand what is happening.
Below is the index.php:
<?php
//Start session
if(!isset($_SESSION)) { session_start(); }
unset($_SESSION['ID']);
unset($_SESSION['REG_NUM']);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portal System</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="static/css/bootstrap.min.css">
<link rel="stylesheet" href="static/css/style.css">
<!-- <link rel="stylesheet" href="static/css/style.css"/> -->
</head>
<body>
<!-- Header -->
<nav class="navbar navbar-fixed-top" style="background-color: green;" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">portal</a>
</div>
</div><!-- /.container-fluid -->
</nav>
<!-- End Header -->
<div class="background">
<div class="container">
<div class="jumbotron bg-success text-warning">
<h1 class="text-center">portal</h1>
<h3 class="text-center"> Welcome to The Portal.</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4">
<div class="login-con">
<h3>Student Log-in</h3><hr>
<?php
if(isset($_SESSION['ERROR_MSG_ARRAY']) && is_array($_SESSION['ERROR_MSG_ARRAY']) && COUNT($_SESSION['ERROR_MSG_ARRAY']) > 0) {
foreach($_SESSION['ERROR_MSG_ARRAY'] as $msg) {
echo "<div class='alert alert-danger'>";
echo $msg;
echo "</div>";
}
unset($_SESSION['ERROR_MSG_ARRAY']);
}
?>
<form action="process/login.php" method="POST" role="form">
<div class="form-group has-warning has-feedback">
<label for="reg_num">Registration Number</label>
<input type="text" name="reg_num" id="reg_num" class="form-control" autocomplete="off" placeholder="Registration Number">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-warning has-feedback">
<label>Password</label>
<input id="password" type="password" autocomplete="off" class="form-control" placeholder="Password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<button type="submit" onclick="showSomeMessage()" name="submit" class="btn btn-info">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
login.php below:
<?php
require("../admin/database.php");
require("../class/StudentLogin.php");
if(isset($_POST['submit'])){
$regnum = trim($_POST['regnumber']);
$password = trim($_POST['password']);
$loginStud = new StudentLogin($reg_num, $password);
$rtnlogin = $loginStud->Studlogin();
}
$conn->close();
?>
Then the StudentLogin class is:
<?php
class StudentLogin
{
private $_regnumber;
private $_password;
public function __construct($c_reg_num, $c_password){
$this->_regnumber = $c_reg_num;
$this->_password = $c_password;
}
public function StudLogin(){
global $conn;
// starting session
session_start();
// valiidate errors
$error_msg_array = array();
// error msg
$error_msg = FALSE;
if($this->_reg_num == ""){
$error_msg_array[] = "Please input your Registration Number";
$error_msg = TRUE;
}
if($this->_password == ""){
$error_msg_array[] = "Please input your password";
$error_msg = TRUE;
}
if($error_msg){
$_SESSION['ERROR_MSG_ARR'] = $error_msg_array;
header("location: http://localhost/project/index.php");
exit();
}
$sql = "SELECT * FROM students WHERE regnumber ='$reg_num' AND password ='$password' LIMIT 1";
if(!$stmt = $conn->prepare($sql)){
echo $stmt->error;
} else {
$stmt->bind_param("ss", $this->_reg_num, $this->_password);
$stmt->execute();
$result = $stmt->get_result();
}
if($result->num_rows > 0) {
// login successful
$row = $result->fetch_assoc();
// session creation
session_regenerate_id();
$_SESSION['reg_num'] = $row["regnunmber"];
$_SESSION['name'] = $row["name"];
session_write_close();
header("location: http://localhost/project/stud_page.php");
} else {
// Login failed
$error_msg_array[] = "The Registration Number and Password you entered is incorrect.";
$error_msg = TRUE;
if($error_msg) {
$_SESSION['ERROR_MSG_ARR'] = $error_msg_array;
header("location: http://localhost/project/index.php");
exit();
}
$stmt->free_result();
}
$result->free();
return $result;
}
}
?>
MySQL database, table students contains the following columns:
$sql="INSERT INTO `students`(`name`, `education`, `regnumber`, `nationality`, `gender`, `phone`, `photo`, `branch`,`password`)
VALUES ('$name','$education','$reg_num','$nationality','$gender','$phone','$target_file','$branch','$ency_pass')";

You have validation on login.php, which is not loaded before form is send.
And if you can i would recommend you using dibi, because this work with database is not properly right and can cause some problems if u are going to use that in production
https://dibiphp.com/en/

Related

error about hashed password don't match in php [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
isset function not working correctly
(1 answer)
Closed 5 years ago.
I am trying to login with a username or email and password in php. As i try to login it says password do not match, as i have typed the correct username and password. I guess something going wrong with my hashing password or session variable. Can anybody help me with my code?
Here is my login.inc.php file
<?php
session_start();
if (isset($_POST['Loginsubmit'])) {
include 'dbh.inc.php';
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password= mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
if (empty($username) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE username= '$username' OR email= '$username'";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: ../index.php?login=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
// De-hashing the password
$hashedPasswordCheck = password_verify($password, $row['password']);
if ($hashedPasswordCheck == false) {
header("Location: ../index.php?login=error");
exit();
} elseif ($hashedPasswordCheck == true) {
// Log in the user here
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['surname'] = $row['surname'];
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
$_SESSION['bdate'] = $row['bdate'];
$_SESSION['gender'] = $row['gender'];
header("Location: ../home.php");
exit();
}
}
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
And here is my part of index.php file where i am taking the inputs
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mysite</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
<link href="css/bootstrapValidator.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrapValidator.min.js" type="text/javascript"></script>
<script src="https://use.fontawesome.com/465fa6787a.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" id="navbar">
<div class="container">
<!-- logo -->
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#myNav">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
BRAND
</div>
<!-- menu items -->
<div class="collapse navbar-collapse" id="myNav">
<div class="nav navbar-nav pull-right">
<form class="navbar-form navbar-right" action="includes/login.inc.php" method="post">
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user"></span>
</span>
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="input-group ">
<span class="input-group-addon">
<span class="glyphicon glyphicon-lock"></span>
</span>
<input type="password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-success" name="Loginsubmit">Login</button>
</form>
</div>
</div>
</div>
</nav>

how to get username and display when is logged in

in this i wannna get the username who is logged in and display it in the home page when the username is correct and registered in database .should i use session and where to use it.how it is been done
<?php
error_log("chk.php executing");
// Get values from form
include 'config.php';
foreach ($_POST as $key => $value) {
error_log($key);
}
//error_log($_POST['username']);
$username=$_POST['username'];
$password=$_POST['password'];
// Insert data into mysql
$qry = mysql_query("SELECT * FROM useraccount WHERE username='$username'");
if(!$qry) {
die("Query Failed: ". mysql_error());
} else {
$row=mysql_fetch_array($qry);
if ($username==$row['username']) {
if($username=='' || $password=='') {
error_log("some fields are empty");
//header("Location:login.php?id=Some fields are empty");
// header("Content-Type: text/html");
// {echo "<b>Some fields are empty</b>";}
} else if($username==$row['username'] && $password==$row['password']) {
error_log("logged in");
header('Location: home.html');
// header("Content-Type: text/html");
// {echo "<b>User name password verified</b>";}
//header("Location: home.html?id=$username");
} else {
error_log("password is incorrect");
// header("Content-Type: text/html");
// {echo "<b>username already taken or your password is incorrect. Please try again</b>";}
//header("Location:.php?id=username already taken or your password is incorrect. Please try again");
}}
else
error_log("username incorrect");
}
mysql_close();
?>
html,body
{
margin:0px;
height:100%;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 60%;
margin: auto;
}
.content
{
width:100%;
height:400px;
}
.signup
{
height:500px;
}
.footer
{
position:relative;
background-color:black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>ASK</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="boot.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6">
<h1>school name</h1>
</div>
<div class="col-md-6">
<img src="../project/photo/l.png" height="150px"/>
</div>
</div>
</div>
</div>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#mynavbar">schoolName</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li><a href="about.html" target=_self>About Us</a></li>
<li><a href="infra.html" target=_self>Infrastructure</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="">Administration<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>staff login</li>
<li>staff details</li>
<li>class handling</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<form class="form-horizontal" action="chk.php" method="POST">
<div class="form-group">
<div class="col-xs-3">
<label for="username">Username:</label>
<input name="username" type="username" class="form-control" id="username" placeholder="Enter username">
</div></div>
<div class="form-group">
<div class="col-xs-3">
<label for="pwd">Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Enter password">
</div></div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label><br>
</div> -->
<button type="submit" class="btn btn-default">Submit</button><br>
</form>
</div>
<div class="footer navbar-fixed-bottom">
<p> Copyrights# ©WWW.schools.com</p>
</div>
</body>
</html>
first of all when username store in session on login time
<?php
session_start();
- List item
error_log("chk.php executing"); // Get values from form include 'config.php';
foreach ($_POST as $key => $value) { error_log($key); } //error_log($_POST['username']); $username=$_POST['username']; $password=$_POST['password']; // Insert data into mysql $qry = mysql_query("SELECT * FROM useraccount WHERE username='$username'"); if(!$qry) { die("Query Failed: ". mysql_error()); } else {
$row=mysql_fetch_array($qry);
if ($username==$row['username']) {
if($username=='' || $password=='') {
error_log("some fields are empty");
//header("Location:login.php?id=Some fields are empty");
// header("Content-Type: text/html"); // {echo "<b>Some fields are empty</b>";}
} else if($username==$row['username'] && $password==$row['password']) {
error_log("logged in");
$_SESSION['username']=$row['username'];
header('Location: home.html');
// header("Content-Type: text/html"); // {echo "<b>User name password verified</b>";}
//header("Location: home.html?id=$username");
} else {
error_log("password is incorrect");
// header("Content-Type: text/html"); // {echo "<b>username already taken or your password is incorrect. Please try again</b>";}
//header("Location:.php?id=username already taken or your password is incorrect. Please try again");
}}
else
error_log("username incorrect"); } mysql_close(); ?>
Another page we get this username and we change file name home.html to home.php
home.php
echo $_SESSION['username'];
?>
output username print this page
You can use SESSION . You have to use session_start() in every files that you want to display the username
else if($username==$row['username'] && $password==$row['password']) {
$_SESSION['username'] = $username; // store username name in session
error_log("logged in");
header('Location: home.html');
// header("Content-Type: text/html");
// {echo "<b>User name password verified</b>";}
header("Location: home.php?id=$username"); // redirect to home.php page
You can simply display the username by echo $_SESSION['username']; Don't forget to add session_start(); in your home.php. For more info please refer to this link http://php.net/manual/en/function.session-start.php
You should use session_start();
After successfully login,you can post username or email like this-
<?php
include_once'dbconnect.php';
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//print logged in user's email as saved in database
echo $userRow['email'];
////print logged in user's username as saved in database
echo $userRow['username'];
?>
This is as per my database where-
'dbconnect.php'is connection file.
'users' is tablename.
You can use session_start(); and store the username into it.
//Initialize the session:
session_start();
<!doctype html>
<head>
.
.
.
</head>
<body>
.
.
<?php
$q = "SELECT * FROM useraccount WHERE username='$username'";
$r = $mysqli->query($q);
if ($r->num_rows == 1) {
$_SESSION = $r-> fetch_array(MYSQLI_ASSOC);
}
?>
.
</body>
</html>
You can take a look at my site for that same query at hiteachers.com

Login authentication not working for my site

The codes for site is given below. Login cannot be authenticated with what I've done. Firstly, it will redirect to the login page as expected if not logged in. Then, after I clearly give the login details correctly, it won't redirect me to the site I want. Instead, it will remain on login page. Please help me...
<!--This is the page that I want to redirect after successful login-->
<?php
session_start();
if($_SESSION['loggedIn'])
{
header('Location: restaurant.php');
}
else
{
header('Location: login.php');
}
?>
<html lang="en">
<head>
<title>Welcome to Foodline</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css">
<link href="css/simple-sidebar.css" rel="stylesheet">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<style>
/* Remove the jumbotron's default bottom margin */
.jumbotron {
margin-bottom: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #f2f2f2;
padding: 25px;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="container text-center">
<h1><font face="Analecta">FOODLINE</font></h1>
<p>We provide the best service for our costumers</p>
</div>
</div>
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand"><font face="Analecta" color="white">>Restaurants<</font></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>
Hamro Didi (HD)
</li>
<li>
HK
</li>
<li>
Junu Hotel
</li>
<li>
Junction Cafe
</li>
<li>
Laxmi Hotel
</li>
</ul>
</div>
</div>
</nav>
<footer class="container-fluid text-center">
<p>Foodline Official Website &copy</p>
<p align="center">Logged in as: <div id="username" align="center"> <span class="glyphicon glyphicon-log-in"></span><?php
if(isset($_GET['id'])){
echo ' '.$_GET['id'];
}
else {
echo '(write) a 404 page';
}
?>
</div>
</p>
</footer>
</div>
<!--This is login.php-->
<?php
//session_start();
include("connection.php");
$msg='';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from form
$username = $_POST['username'];
$password = $_POST['password'];
// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//Input Validations
if($username == '') {
$_SESSION["login_user"] = $username; $msg = "Username missing";
header("location: login.php?msg=$msg");
}
if($password == '') {
$msg = "Password missing";
header("location: login.php?msg=$msg");
}
//Create query
$qry="SELECT * FROM user WHERE user_name='$username' AND user_password='$password'";
$result =mysql_query($qry)or die(mysql_error());
$output=mysql_fetch_assoc($result);
//Check whether the query was successful or not
if(!empty($output)) {
//Login Successful
$_SESSION['name']= $username;
$_SESSION['loggedIn'] = true;
header("location:restaurant.php?id=$username");
}
else {
//Login failed
$msg= "user name and password not found";
header("location:login.php?msg=$msg");
}
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<style>
.jumbotron {
margin-bottom: 0;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="container text-center">
<h1><font face="Analecta">FOODLINE</font></h1>
<p>We provide the best service for our costumers</p>
</div>
</div>
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.php">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Restaurants</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<h2><font face="Analecta">>Login from here<</font></h2>
<form role="form" name="login" action="login.php" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" placeholder="Enter username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" placeholder="Enter password" required>
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" value="login">Submit</button>
<br>
<br>
<?php
$msg = (isset($_GET['msg']) ? $_GET['msg'] : null); //GET the message
if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it
?>
</form>
<p>Not a user yet? Sign up here</p>
</div>
<footer class="container-fluid text-center">
<p>Foodline Official Website &copy</p>
<p>Get deals:
<span class="glyphicon glyphicon-menu-right"></span>SignUp
</p>
</footer>
</body>
</html>
Uncomment:
//session_start();
From line 5 in login.php and change to this:
if(! $_SESSION['loggedIn']) {
header('Location: login.php');
}
in restaurant.php.

PHP SQL won't update the data

Update as of 23rd June 2015
The update query still not working. Took an advice from Rene Kross and made some code cleanup and stumbled upon a few part missing semicolons and etc however the update query are still not working.
Here's the adminUpdate.php
<?php
require 'Connect.php';
$staffID = null;
if ( !empty($_GET['staffID'])) {
$staffID = $_REQUEST['staffID'];
}
if ( null==$staffID ) {
header("Location: ManageAdministrator.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$adminNameError = null;
$emailError = null;
$SKGError = null;
$ExtnError = null;
// keep track post values
$adminName = $_POST['adminName'];
$email = $_POST['email'];
$SKG = $_POST['SKG'];
$Extn = $_POST['Extn'];
// validate input
$valid = true;
if (empty($adminName)){
$adminNameError = "Please enter Administrator Name";
$valid = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valid = false;
}
if (empty($SKG)) {
$SKGError = 'Please choose SKG';
$valid = false;
}
if(empty($Extn)){
$ExtnError = "Please enter Extension Number";
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE admin set adminName ='$adminName', email ='$email', SKG ='$SKG', Extn ='$Extn' WHERE staffID = '$staffID'";
$q = $pdo->prepare($sql);
$q->execute(array($staffID,$adminName,$email,$SKG,$Extn));
Database::disconnect();
header("Location: ManageAdministrator.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM admin where staffID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($staffID));
$data = $q->fetch(PDO::FETCH_ASSOC);
$adminName = $data['adminName'];
$email = $data['email'];
$SKG = $data['SKG'];
$Extn = $data['Extn'];
$password = $data['password'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Update Administrator</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Capability Management">
<!-- CSS External Link -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/sb-admin.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<div id="wrapper">
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="HomePage.php"><b> Training Log Database </b></a>
</div>
<ul class="nav navbar-right top-nav">
<li class="dropdown">
<!-- PHP REFER LOGIN NAME-->
<i class="fa fa-user"></i> M Farhan M Fazli <b class="caret"></b>
<ul class="dropdown-menu">
<li>
<i class="fa fa-fw fa-user"></i> Profile
</li>
<li class="divider"></li>
<li>
<!-- PHP LOGOUT FUNCTION -->
<i class="fa fa-fw fa-power-off"></i> Log Out
</li>
</ul>
</li>
</ul>
<!-- Sidebar Menu Items start here -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li>
<i class="fa fa-fw fa-dashboard"></i> Home
</li>
<li>
<i class="fa fa-fw fa-bar-chart-o"></i> Manage Administrator
</li>
<li>
<!-- Add new pages here -->
<i class="fa fa-fw fa-bar-chart-o"></i> Manage Staff
</li>
<li>
<i class="fa fa-fw fa-edit"></i> Manage Training<i class="fa fa-fw fa-caret-down"></i>
<ul id="demo" class="collapse">
<li>
Training Information
</li>
<li>
TBA
</li>
</ul>
</li>
<li>
<i class="glyphicon glyphicon-wrench"></i> Tools for Administrator<i class="fa fa-fw fa-caret-down"></i>
<ul id="demo1" class="collapse">
<li> Add News </li>
<li> Add Announcement </li>
<li> Search News </li>
<li> Search Announcement </li>
<li> View My Post </li>
</ul>
</li>
<li>
<i class="glyphicon glyphicon-info-sign"></i> About
</li>
<li>
<i class="glyphicon glyphicon-question-sign"></i> FAQs
</li>
</div>
<!-- /.navbar-collapse -->
</nav>
<div id="page-wrapper">
<div class="container-fluid">
<div class="row col-lg-12">
<h2 class="page-header"> Update Administrator Account </h2>
<div class="row col-lg-12">
<h3> Administrator details </h3>
<div class="row col-lg-12">
<form class="form-horizontal form-group" action="adminUpdate.php?id=<?php echo $staffID?>" method="post">
<!-- <div class="form-group col-lg-12 <?php echo !empty($staffIDError)?'error':'';?>">
<label>Administrator Staff ID</label>
<input class="form-control" name="staffID" type="text" value="<?php echo !empty($staffID)?$staffID:'';?>">
<?php if (!empty($staffIDError)): ?>
<span class="help-inline"><?php echo $staffIDError;?></span>
<?php endif; ?>
</div>-->
<div class="form-group col-lg-12 <?php echo !empty($adminNameError)?'error':'';?>">
<label>Administrator Name</label>
<input class="form-control" name="adminName" type="text" value="<?php echo !empty($adminName)?$adminName:'';?>">
<?php if (!empty($adminNameError)): ?>
<span class="help-inline"><?php echo $adminNameError;?></span>
<?php endif; ?>
</div>
<div class="form-group col-lg-12 <?php echo !empty($emailError)?'error':'';?>">
<label>Administrator Email</label>
<input class="form-control" name="email" type="text" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $emailError;?></span>
<?php endif; ?>
</div>
<div class="form-group col-lg-12 <?php echo !empty($ExtnError)?'error':'';?>">
<label> Extension Number </label>
<input class="form-control" name="Extn" type="text" value="<?php echo !empty($Extn)?$Extn:'';?>">
<?php if (!empty($ExtnError)): ?>
<span class="help-inline"><?php echo $ExtnError;?></span>
<?php endif; ?>
</label>
</div>
<div class="form-group col-lg-12 <?php echo !empty($SKGError)?'error':'';?>">
<label>SKG</label>
<select class="form-control" name="SKG" value="<?php echo !empty($SKG)?$SKG:'';?>">
<option> SKG 09 </option>
<option> SKG 18 </option>
<option> SKG 20 </option>
<option> SKG 16 </option>
<option> SKG 11 </option>
<option> SKG 13 </option>
<option> SKG 14 </option>
<option> SKG 12 </option>
<option> SKG 15 </option>
<option> SKG 10 </option>
<option> SKG 25 </option>
</select>
<?php if (!empty($SKGError)): ?>
<span class="help-inline"><?php echo $SKGError;?></span>
<?php endif; ?>
</div>
<!-- <div class="form-group col-lg-12 <?php echo !empty($passwordError)?'error':'';?>">
<label>Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password" value="<?php echo !empty($password)?$password:'';?>">
<?php if (!empty($passwordError)): ?>
<span class="help-inline"><?php echo $passwordError;?></span>
<?php endif; ?> -->
</div>
<div class="form-actions col-lg-12">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn btn-default" href="ManageAdministrator.php">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div><!--wrap-->
</body>
</html>
Here's the Connect.php
<?php
class Database
{
private static $dbName = 'tlad' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'root';
private static $dbUserPassword = '';
private static $cont = null;
public function __construct() {
exit('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
Here's my table:
As I mentioned earlier, the read, create and delete function are working except for this update function aren't.
Please note: I've followed a tutorial on creating a CRUD datatable, while his template worked but my code aren't. Here's the tutorial's code for update template:
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$emailError = null;
$mobileError = null;
// keep track post values
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valid = false;
}
if (empty($mobile)) {
$mobileError = 'Please enter Mobile Number';
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers set name = ?, email = ?, mobile =? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$mobile,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$mobile = $data['mobile'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update a Customer</h3>
</div>
<form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($emailError)?'error':'';?>">
<label class="control-label">Email Address</label>
<div class="controls">
<input name="email" type="text" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($mobileError)?'error':'';?>">
<label class="control-label">Mobile Number</label>
<div class="controls">
<input name="mobile" type="text" value="<?php echo !empty($mobile)?$mobile:'';?>">
<?php if (!empty($mobileError)): ?>
<span class="help-inline"><?php echo $mobileError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Your execute has 5 parameters, but query wants 6.
$sql = "UPDATE admin set staffID = ?, adminName = ?, email = ?, SKG = ?, Extn = ? WHERE staffID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($staffID, $adminName, $email, $SKG, $Extn, $staffID));
Also were missing $ in front of email, SKG and Extn.

Unable to return to 'User Profile' page after login

I have login.php page for the user to login their credentials. After the user logs in that is when the doLogin.php page will be displayed. In other words their user profile will be displayed. On the User Profile element, there is an edit button which leads them to editProfile.php page to edit their personal info. However when I clicked the back arrow on my tab to go to the User profile page back an error "Confirm Form Resubmission" was displayed. How do I counter this such that when the user wished to go back to the User Profile page, their details will be displayed?
This is my doLogin.php
session_start();
$msg = "";
//check whether session variable 'user_id' is set
//in other words, check whether the user is already logged in
if (isset($_SESSION['user_id'])) {
$msg = "You are already logged in.<br/><a href='index.php'>Home</a>";
$msg = "<a href ='logout.php'>logout</a>";
} else { //user is not logged in
//check whether form input 'username' contains value
if (isset($_POST['username'])) {
//retrieve form data
$entered_username = $_POST['username'];
$entered_password = $_POST['password'];
//connect to database
include ("dbfunctions.php");
//match the username and password entered with database record
$query = "SELECT *from role,user
WHERE user_name='$entered_username' AND
PASSWORD = SHA1('$entered_password') AND user.role_id = role.role_id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$query2 = "SELECT * FROM user,country where user.country_id=country.country_id ORDER BY `user`.`id` ASC ";
$result2 = mysqli_query($link, $query2) or die(mysqli_error($link));
$query3 = "SELECT * FROM book";
$result3 = mysqli_query($link, $query3) or die(mysqli_error($link));
if (mysqli_num_rows($result) == 1) {
$update = "UPDATE `user` SET last_login = NOW() WHERE user_name='$entered_username' ";
$resultupdate = mysqli_query($link, $update);
$row = mysqli_fetch_array($result);
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['user_name'];
$_SESSION['email'] = $row['email_address'];
$_SESSION['gender'] = $row['gender_id'];
$_SESSION['role_id'] = $row['role_type'];
$_SESSION['lastlog'] = $row['last_login'];
$msg1 = $_SESSION['username'];
$msg2 = "<b>Gender: </b> " . $_SESSION['gender'] . "<br/>";
$msg3 = "<b>Email: </b>" . $_SESSION['email'] . "<br/>";
$msg4 = "<b>Your last visit on this site: </b>" . $_SESSION['lastlog'];
$msg .= "You are logged in as " . $_SESSION['role_id'] . "<br/>";
$rowz = mysqli_fetch_array($result3);
} else { //record not found
$msg = "<p>Sorry, you must enter a valid username and password to log in.<a href='login.php'>Back</a></p>";
}
}
and this is my editProfile.php
// include a php file that contains the common database connection codes
include ("dbfunctions.php");
session_start();
$userID = $_POST['userID'];
$queryedit = "SELECT * FROM user WHERE id=$userID";
// execute the query
$resultedit = mysqli_query($link, $queryedit) or die(mysqli_error($link));
// fetch the execution result to an array
$rowedit = mysqli_fetch_array($resultedit);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="style.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css" />
<script src="script.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="styles.css">
<title>Edit Profile & Settings</title>
</head>
<body>
<div class="container">
Sign Out
<div class="page-header">
<h1>OBC <small>onlinebookclub</small></h1>
<div class="row">
<div class="col-lg-6">
<form method="post" action="doSearch.php">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go!</button>
</span>
<input type="text" class="form-control" placeholder="Title/Author/YearOfPublish">
</form>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
</div>
</div>
<!-- Registration Form - START -->
<div class="container" id="container1">
<div id='cssmenu'>
<ul>
<li class='active'><a href='#'>Profile</a></li>
<li><a href='addbook.php'>Add/Edit Books</a></li>
<li><a href='#'>Add/Edit Authors</a></li>
<li><a href='editProfile.php'>Edit Profile & Settings</a></li>
</ul>
</div>
<h2>Edit Profile</h2>
<hr>
<div class="row">
<!-- left column -->
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar img-circle" alt="avatar">
<h6>Upload a different photo...</h6>
<input type="file" class="form-control">
</div>
</div>
<!-- edit form column -->
<div class="col-md-9 personal-info">
<h3>Personal info</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-lg-3 control-label">Username:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo $rowedit['user_name'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo $rowedit['email_address'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input type="hidden" name="id" value="<?php echo $rowedit['id'] ?>" />
<input type="submit" class="btn btn-primary" value="Save Changes">
<span></span>
<input type="reset" class="btn btn-default" value="Cancel">
</div>
</div>
</form>
</div>
</div>
</div>
<style>
#container1 {
background-color: #e2dada;
opacity: 0.9;
border-radius: 2em;
}
.centered-form {
margin-top: -185px;
margin-bottom: 120px;
}
.centered-form .panel {
background: rgba(255, 255, 255, 0.8);
box-shadow: rgba(0, 0, 0, 0.3) 20px 20px 20px;
}
h2{
color: orange;
}
</style>
</body>
First Way
One way of handling such errors is to redirect the page to itself.
i.e when the user logs in and when you show the doLogin page, i.e the user profile page, ry to use the header() function
header('Location:doLogin.php');
Second Way
You can make an AJAX redirect using jQuery or something

Categories