Jump to content

I want to update an employee profile as an admin but it not update and shows a warning in the placeholder for the unique id


Go to solution Solved by mac_gyver,

Recommended Posts

<?php
//updateemployee.php
session_start(); //Resume session
if(isset($_SESSION['name'])){// If $_SESSION['name'] not set, force redirect to home page 
		$name = $_SESSION['name'];
		$status_msg="";
		if (isset($_GET['data'])){
		$data = $_GET['data'];
		if(isset($_GET['update'])){
		if(isset($_GET['name']) && isset($_GET['email'])&& isset($_GET['gender']) && isset($_GET['faculty'])){
			if(!empty($_GET['name']) && !empty($_GET['email'])&& !empty($_GET['gender']) && !empty($_GET['faculty'])){
					//$data = $_GET['data'];
					$new_name = $_GET['name'];
					$new_email = $_GET['email'];
					$new_gender = $_GET['gender'];
					$new_school = $_GET['faculty'];
					$conn= connectDB();
					$status_msg=updateRecord($new_name,$new_school,$new_gender,$conn,$new_email,$data);
					echo $new_name;
					echo $new_school;
					echo $new_gender;
					echo $new_email;
					echo $data;
		}else{
			$status_msg="<h2 style='color:red;'>Incomplete Input. Please try again</h2>";
		}
	}
}
}}else{
	header('Location: index.php');
}

if(isset($_GET['logout'])){
	session_destroy();
	header('Location: index.php');
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
 <body>
<?php
if(isset($_GET['data'])){
	$data = $_GET['data'];
	echo $data;//To test if the Id matches the profile that needs to be updated
}
$status_msg = "";
function connectDB(){//Function to connect to database
	$servername = "localhost";
	$username = "root";
	$password = "";
	$db= "staff_db";
	
	$conn = mysqli_connect($servername,$username,$password,$db);
	
	if(!$conn){
		die('Connection Failed: '.mysqli_connect_error());
	}
	return $conn;
}

//$sql = "SELECT * FROM staff_table WHERE staff_id='$data'";
$conn = connectDB();

function updateRecord($new_name,$new_gender,$new_school,$conn,$new_email,$data){

	$sql = "UPDATE staff_table SET name='$new_name',gender='$new_gender',school='$new_school',email='$new_email' WHERE staff_id='$data'";
	
	if (mysqli_query($conn,$sql)){
		$status_msg="<h3 style= 'color:green;'>Account details are successfully updated.</h3>";
	}else{
		$status_msg= "ERROR: Could not execute SQL".mysqli_error($conn);
	}
	mysqli_close($conn);
	return $status_msg;
}


 ?>
<h1>Update Staff Profile</h1>
<form action="UpdateEmployee.php" method="GET">
<fieldset>
<legend>Personal Information</legend>
<p><span class="error">* required field</span></p>
<label for="name">Full Name: <input type="text" id="name" name="name"><span class="error">*</span></label><br>
<label for="sID">Staff ID: <input type="text" id="sID" name="sID" placeholder="<?php echo $data;?>" disabled="disabled"></label><br>
<label for="email">Email: <input type="text" id="email" name="email"><span class="error">*</span></label><br>
<label for="gender">Gender:</label>
	<select id="gender" name="gender">
	<option value = "-1" selected>[Gender]</option>
	<option value = "Male">Male</option>
	<option value = "Female">Female</option>
	</select><br>
<label for="faculty">School/Faculty</label>
 	<select id="faculty" name="faculty">
	<option value = "-1" selected>[School/Faculty]</option>
	<option value = "SFS">SFS</option>
	<option value = "FBDA">FBDA</option>
	<option value = "FECS">FECS</option>
	</select><br>
<p><input type="submit" name="update" value="Update Staff"></p>
<p><?php echo $status_msg;?></p>
</fieldset>
</form>
<footer>
<p><a href="MainMenu.php">Main Menu</a></p>
<p><a href="">Logout</a></p>
</footer>
</body>
</html>
<?php
//displayemployeeinf.php
session_start(); //Resume session

if(isset($_SESSION['name'])){// If $_SESSION['name'] not set, force redirect to home page 
		$name = $_SESSION['name'];
}else{
	header('Location: index.php');
}

if(isset($_POST['logout'])){
	session_destroy();
	header('Location: index.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Display Employee Information</title>
</head>

<body>
<h1>Staff Profile</h1>
<div class="display">
<fieldset>
<legend>Employees Information</legend>
<?php
function connectDB(){//Function to connect to database
	$servername = "localhost";
	$username = "root";
	$password = "";
	$db= "staff_db";
	
	$conn = mysqli_connect($servername,$username,$password,$db);
	
	if(!$conn){
		die('Connection Failed: '.mysqli_connect_error());
	}
	return $conn;
}

$data = $_GET['data'];

$sql = "SELECT * FROM staff_table WHERE name ='$data'";
$conn= connectDB();
$result = mysqli_query($conn,$sql);

if($result){
	$row = mysqli_fetch_assoc($result);
}

if(isset($_POST['update'])){
	header('Location: UpdateEmployee.php?data='.$row['staff_id'].'');
}
?>
<form method="POST">
<table class="center">
	<tr><td><p><strong>Name:</strong></p></td><td><p><?php echo $row['name'];?></p></td></tr>
	<tr><td><p><strong>Staff ID:</strong></p></td><td><p><?php echo $row['staff_id'];?></p></td></tr>
	<tr><td><p><strong>Email</strong></p></td><td><p><?php echo $row['email'];?></p></td></tr>
	<tr><td><p><strong>Gender</strong></p></td><td><p><?php echo $row['gender'];?></p></td></tr>
	<tr><td><p><strong>School</strong></p></td><td><p><?php echo $row['school'];?></p></td></tr>
</table>
	<p><input type="submit" name="update" value="Update"></p>
	<p><input type="submit" name="delete" value="Delete"></p>
</form>
</fieldset>
</div>
<footer>
<p><a href="MainMenu.php">Main Menu</a></p>
<p><a href="">Logout</a></p>
</footer>
</body>
</html>

 

2022-11-19 16-29-43 localhost   127.0.0.1   staff_db   staff_table   phpMyAdmin 5.2.0, group Cos30020 — Yandex Browser.png

  • Solution

you are using a post method form, followed by an unnecessary redirect, to select which record to edit and then a get method form for updating the data. this is backwards. you should use get inputs to determine what will be displayed on a page and a post method form when performing an action on the server, such as updating the data. also, you can and should do all of this on one page to avoid repetition of code.

the code for any page should be laid out in this general order -

  1. initialization
  2. post method form processing
  3. get method business logic - get/produce data needed to display the page
  4. html document

when you display the existing records, the edit button should be a get method link with the id as part of the link. when you click one of those links, the resulting code that gets executed would query to get the  existing row of data to populate the form field values, but only if the update form has never been submitted. if the update form has been submitted, you would not execute this query. the way to accomplish this 'interlocking' of the data being edited is to use an internal 'working' array variable to hold this data, then use elements in this array variable through out the rest of the code. inside the post method form processing logic, you would store a trimmed copy of the $_POST form data in this variable. at the point of querying for the initial data, if this variable is empty, you would execute the query.

here are some issues with and things that will simplify the posted code -

  1. your login system should only store the user id in the session variable upon successful login, then query on each page request to get any other user information, such as the user's name, permissions.
  2. your code should check if the current logged in user is an admin before allowing access to the edit logic.
  3. when conditional 'fail' code is much shorter than the 'success' code, if you invert the condition being tested and put the fail code first, it results in clearer, cleaner code. also, since the fail code is a redirect in this case, which must have an exit/die statement to stop php code execution, you can eliminate the else {} part of the conditional test since the redirect/exit/die will stop the execution for a non-logged in user.
  4. don't copy variables to other variables for nothing. this is just a waste of typing and introduces errors.
  5. don't use multiple names for the same piece of data. whatever the actual meaning of the data is, use that name throughout the code. one such example is the staff_id value being called 'data' and at another point it is a name value.
  6. since you will be switching to use a post method form for the update operation, after you detect if a post method form has been submitted, all the form fields (except for unchecked checkbox/radio fields) will be set. there will be no need for a massive list of isset() statements.
  7. you should put the database connection code in a separate .php file, then require it when needed.
  8. you should not unconditionally echo database errors onto the web page, which will only help hackers when they internationally trigger errors. instead, use exceptions for database statement errors an in most cases let php catch and handle the exception. the exception to this rule is when inserting/updating user submitted data that can result in duplicate or out of range values, which is something that you are doing. in this case, your code should catch the exception, test if the error number is for something that your code is designed to handle, and setup a message letting the user know what was wrong with the data that they submitted. for all other error numbers, just re-throw the exception and let php handle it.
  9. the logout operation should use a post method form.
  10. any function definitions should either be in the initialization section of code or be in their own .php files that get required in the initialization section of code.
  11. your application should not use the root user without any password. instead, create a specific database user with a password with only the  permissions that it needs for you application.
  12. the updateRecord function should only have two call-time parameters. an array of the input data and the database connection.
  13. the updateRecord should not contain any application specific html markup. this should be handled in the calling code. the function should only return a true or false value to the calling code.
  14. don't put external, unknown, dynamic values directly into sql query statements. you must protect against sql special characters in data values from being able to break the sql syntax, which is how sql injection is accomplished. the fool-proof way of doing this is to use prepared queries. since the mysqli extension's prepared query interface is overly complicated and inconsistent, this would be a good time to switch to the more modern and simple PDO database extension.
  15. the updateRecord function should not close the database connection. it is not the responsibility of this function to do this, only to update the recorded.
  16. the update form should populate the form field values and preselect the option that matches the initial existing data being edited, then populate/preselect using the submitted form data, as described above.
  17. any dynamic value that you output on a web page should have htmlentities() applied to it to help prevent cross site scripting.
  18. the value attribute for the select/option 1st prompt option should be an empty string.
  19. since you are putting the <label></label> tags around the form field they belong with, you don't need the for='...' and matching id='...' attributes.

the post method form processing code should -

  1. detect if a post method form was submitted.
  2. keep the form data as a set in an array variable.
  3. trim all the input data as at once. after you do item #2 on this list, you can do this with one php statement.
  4. validate all the inputs, storing validation errors in an array using the field name as the array index.
  5. after the end of all the validation logic, if there are no errors, use the form data.
  6. after using the form data, if there are no errors, redirect to the exact same url of the current page to cause a get request for the page.
  7. if you want to display a one-time success message, store it in a session variable, then test, display, and clear the session variable at the appropriate location in the html document.
  8. if there are errors at step #5 or #6 on this list, the code would continue on to display the html document, where you would test for and display any errors, and redisplay the form, repopulating the field values/selected option choices with the values that are in the 'working' array variable holding the submitted form data.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.