display username based results, when logged in as another user (teacher tracking) - php

I have the following php page in which I am trying to simulate a simple example of searching for a specific username (stored in the database) and when "submit" is clicked, the results for that user are displayed on the page. At the moment, the code shows the results displayed only for the user that is logged in. How do I adapt it to fit with the code to search and track as another user?
HTML:
<p>Welcome, teachers! Here you can track student progress.</p>
<p>Enter the username of the student you wish to 'view' results for</p>
<form action="/action_page.php">
Username: <input type="text" name="FirstName" value="Mickey"><br>
<input type="submit" value="Submit">
</form>
Php related code that only allows the page to load if the user is logged in:
session_start();
if (!isset($_SESSION['username']) or ($_SESSION['username'] == '')) {
header("Location: login.php");
}
?>
Php code that displays the currently logged in user's quiz results:
<table class="table table-hover" style="text-align:center;">
<thead>
<tr>
<th style="text-align:center;">Quiz</th>
<th style="text-align:center;">Score (%)</th>
<th style="text-align:center;">Certificate</th>
<th style="text-align:center;">Retake</th>
</tr>
</thead>
<tbody>
<?php
$a = new NewQuizScore;
$scores = $a->getScores($_SESSION['username']);
foreach ($scores as $score) {
echo ("<tr>");
echo ("<td>".$score[0]. "</td> ");
echo ("<td>".$score[1]. "</td> ");
echo ('<td>Print Certificate</td>');
echo ("<td>Take it again!</td> ");
echo ("</tr>");
}
?>
</tbody>
</table>
</div>
</div>
To reiterate, as a php newbie, I would like a solution (with code in my existing context provided) for how to use the search button to look up a username, and then provide the information for the SEARCHED FOR username in the page, rather than for the username that is logged in. I've tried various things and cannot come up with the logic.
What I've tried:
Along the lines of:
<form action="/action_page.php">
Username: <input type="text" name="username1" value="username1"><br>
and:
$a = new NewQuizScore;
$scores = $a->getScores($_SESSION['username1']);
I was trying to link what is entered in the text box, to the getScores session, but obviously this doesn't work:
Update based on suggested answer - still doesn't work:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'includes/newquizscore.php';
session_start();
if (!isset($_SESSION['username']) or ($_SESSION['username'] == '')) {
header("Location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="#" method="post">
Username: <input type="text" name="username1" value=""><br>
<input type="submit" value="Submit">
</form>
<?php
$username = (!empty($_POST['username1']))? $_POST['username1'] : $_SESSION['username'];
$a = new NewQuizScore;
# This is assuming this action is what you use to get the user's data
$scores = $a->getScores($username)
?>
</body>
</html>

You need to get the value from the form using the $_POST superglobal. $_POST is less transparent than $_GET, so I would use that for your form:
<!-- ADD METHOD ------------------------------->
<!------------------------------vvvvvvvvvvvvv-->
<form action="/action_page.php" method="post">
Username: <input type="text" name="username1" value=""><br>
<input type="submit" value="Submit">
</form>
When you post the form, you can use the script below. Note, since your form is pointing to /action_page.php, that is where this script should be located:
# Fetch the post value OR the current logged in (depending if form submitted or not)
# This is assuming you are searching by username1 value from form
# (since that is what you have in your form). You can use functions like
# trim() to remove empty spaces before and after submitted value to clean
# the input up a bit
$username = (!empty($_POST['username1']))? $_POST['username1'] : $_SESSION['username'];
$a = new NewQuizScore;
# This is assuming this action is what you use to get the user's data
$scores = $a->getScores($username);

Related

Re-populate fields after form submission and redirection PHP ONLY

I am supposed to have my form elements repopulate using php and html only after I click the link from page two. However, none of the fields are repopulating. Please help me!!?
Page 1:
<?php
session_start();
?>
<?php
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<?php
$load_date = $_COOKIE['load_date'];
$_SESSION['is_cool'] = $_POST['is_cool'];
$_SESSION['like_bands'] = $_POST['like_bands'];
$_SESSION['other_band'] = $_POST['other_band'];
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
print_r($bands);
echo $other_band;
echo $is_cool;
?>
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value= "yes" <?php if ($is_cool == 'yes') {
echo 'checked = "yes"';
}?>>
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?>> Black Sabbath</option>
<option value="Mastodon" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?> >Mastodon</option>
<option value="Metallica" <?php if (isset($_SESSION['like_bands']) && in_array("Metallica", $bands)) {
echo 'selected';
} ?> >Metallica</option>
<option value="Swift" <?php if (isset($_SESSION['like_bands']) && in_array("Swift", $bands)) {
echo 'selected';
} ?> >Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit" name= 'submit' value = 'submit'> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
echo $_SESSION['is_cool'];
if (isset($_SESSION['like_bands'])) {
header('Location: hw_page2.php');
}
?>
</body>
</html>
My second Page:
<?php
session_start();
/*
This page should:
1) Transfer back to hw_page1.php if loaded directly without the survey being completed (no survey data in session).
2) Display the Survey Data submitted from the previous page.
3) The form in this page should submit to THIS PAGE.
Use PHP to validate that the form below is completed.
Validate that the signature is not the empty string or only blank spaces (use PHP trim() function)
And of course validate that the checkbox was checked.
If the validation passes, save the signature into SESSION ande transfer to hw_page3.php.
If the validation fails, don't transfer.
Instead, back through to the form in this page WITH an appropriate message.
In that case, the Survey Data MUST also re-display in this page.
Note:
hw_page1.php used client-side JavaScript validation to ensure that all data was collected.
For the form below. do NOT use client-side JavaScript validation, but rather use PHP as instructed above.
Client-side validation is convenient for the end user, but can be bypassed by someone with know-how.
*/
?>
<?php
if (!isset($_SESSION['is_cool']) and !isset($_SESSION['like_bands'])) {
header('Location: hw_page1.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Verify Profile</title>
</head>
<body>
<?php
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
echo $is_cool;
print_r($bands);
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
$bandslist = "";
foreach ($bands as $band) {
$bandslist .= "$band, ";
}
?>
<!-- Display Survey Data Here -->
<table width="" border="1" cellspacing="0" cellpadding="5">
<tr valign="top">
<td>Are you cool?</td>
<td>Liked Bands</td>
<td>Other Favorite Band</td>
</tr>
<tr valign="top">
<td><?= $_SESSION['is_cool']; ?></td>
<td><?= $bandslist; ?></td>
<td><?= $other_band; ?></td>
</tr>
</table>
<br><br>
<form action="hw_page2.php" method="GET" >
Verify that your profile data shown above is accurate by signing below.
<br>
<input type="text" name="signature" value="" placeholder="Sign Here">
<br>
<input type="checkbox" name="user_certify" value="yes">
I certify, under penalty of purgery, that my profile is accurate.
<br><br>
<button type="button" onclick="window.location='hw_page1.php';"> Go Back: Edit Profile Before Signing </button>
<!-- This is NOT a Submit Button! -->
<br>
<button type="submit"> Record Profile </button>
<!-- This is obviously -->
</form>
</body>
</html>
Please help me figure out where I am making a mistake! I have been working on it for days but I cannot figure out the answer.

Simple PHP login not working

I'm very new to PHP and I'm trying to build a webpage with a login page. I think I understand it but my login page isn't working even though its very basic.
This is my file structure at the moment:
http://imgur.com/a/zVcPK
This is the idx (index):
<?php
error_reporting( E_ALL );
ini_set( "display_errors", 1 );
include 'templates/header.php';
if(!isset($_SESSION['logged'])){
include 'controller/login.php';
}else{
if($_SESSION['logged'] == true){
include "controller/navigation.php";
}else{
include "idx.php";
}
}
include 'templates/footer.php'
?>
This is the login.php template:
<?php
$out = "<form method='POST' action='idx.php'>
<p>Login:</p>
<label>Username:</label><input type='text' name ='username' required />
<label>Password:</label><input type='password' name'password' required />
<input type='submit' value='submit' name=submit'/>
</form>";
echo $out;
This is the login.php controller:
<?php
include "view/login.php";
if(isset($_POST['submit'])){
$urn=$_POST['username'];
$pwd=$_POST['password'];
$user = new user($urn);
$worked = $user->authenticate($urn, $pwd);
if($worked == true){
$_SESSION['logged']=true;
$_SESSION['username']=$urn;
header('Location: controller/navigation.php');
}
else
{
echo('Error');
}
}
?>
This is the user model:
<?php
class user
{
private $username;
function __construct($username)
{
$this->username=$username;
}
function authenticate($username, $password)
{
if ($username == 'tim' && $password == 'ttt') {
return true;
} else {
return false;
}
}
}
?>
I'm just trying to get the form to take in the users details, check that they are "tim" and "ttt" and if so return a true value which will prompt the controller to change the header URL to navigation.php controller which in turn shows the navigation.php view which will just be a list of links. For some reason though whenever I hit submit nothing happens, it just stays on the login page.
I know this is a pretty basic thing to do but I've been stuck on it for a couple of days now and I've watched hours and hours of videos on it and read dozens of pages explaining how MVC works but can't get this simple thing done. Please can somebody tell me whats going wrong.
Make sure you start the session on every page you want to get or set session variables.
session_start()
It should be as simple as that, and it threw me for a loop for quite a while.
Have you considered using an MVC framework? They are very helpful for keeping everything tidy and organized, as well as providing a library of helpful functions and classes. CodeIgniter is a great and easy to use framework that is super lightweight. Laravel is a lot more invovled and is better suited for large scale projects.
Change this:
<input type='password' name'password' required />
This:(You missed = name='password')
<input type='password' name='password' required />
And dont forget to add session_start() at the very top of your page.
I will share you my sample PHP login page setup.
it has 3 pages, index, admin, logout
index.php: Creates a form asking username and password, once correct username pssword given (here admin, password) it will create a new session "login". Once logged in it will redirect to the admin.php $validuser ensures previous login is true or not.
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if (isset($_POST["sub"]))
{
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if (!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if ($validUser)
{
header("Location: /admin.php");
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<center>
<h1>Login</h1>
<table>
<form name="input" action="" method="post">
<tr>
<th>
<label for="username">Username</label>
</th>
<th>
<input type="text" value="" id="username" name="username" />
</th>
</tr>
<tr>
<th>
<label for="password">Password</label>
</th>
<th>
<input type="password" value="" id="password" name="password" />
</th>
</tr>
<tr>
<th></th>
<th>
<input type="submit" value="Login" name="sub" />
</th>
</tr>
</form>
</table>
</center>
</body>
</html>
admin.php: Checks for session "login", if session was set then it will proceed further otherwise it will go to login.php
<?php
session_start();
if (!isset($_SESSION['login']))
{
header('LOCATION:login.php');
die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
<center>
<h1>Succesfully logged in</h1>
<input type="button" value="Logout" onclick='window.open("/logout.php","_self")'/>
</center>
</body>
</html>
logout.php: Clears the session, cookies and close them and returns to login.php
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name() , '', 0, '/');
session_regenerate_id(true);
header("Location: /index.php");
die();
?>
put them in same folder it will work.

mysql table not deleting values

I have a mysql data table that holds user information such as name,department,extension and phone number
Now I have a delete query that deletes a user based on the extension number the admin enters.
It was working yesterday and I have not changed a thing so I have no idea what could be wrong.
According to my code it must delete the user and then display the table. Now it does all that but the user still exists.
<?php
error_reporting(0);
require ("database.php");
session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
if($_POST['action'])
{
$this_user_ext =$_GET['extension'];
// sending query
mysql_query("DELETE FROM users WHERE extension = '$this_user_ext'")
or die(mysql_error());
include('maildelete.php');
$extension=$_POST['extension'];
header("Location: index.php");
}
?>
<center>
<form action="" method="post">
Enter 4 Digit Extension Number :
<br>
<input type="text" name="extension">
<br>
<h2>
<input type="submit" name="action" value="Delete Extension">
<br>
</h2>
<h3>
Main Menu
</h3>
</form>
</center>
You have used POST method but you are using $_GET so
change $this_user_ext =$_GET['extension']; to $this_user_ext =$_POST['extension'];
Inside your form's tag having a method POST. You're sending the POST request, not the GET request. Use this code instead $this_user_ext = $_POST['extension'];
<?php
error_reporting(0);
require ("database.php");
session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
if($_POST['action'])
{
$this_user_ext =$_POST['extension'];
// sending query
mysql_query("DELETE FROM users WHERE extension = '".$this_user_ext."'")
or die(mysql_error());
include('maildelete.php');
$extension=$_POST['extension'];
header("Location: index.php");
}
?>
<center><form action="" method="post">
Enter 4 Digit Extension Number :<br><input type="text" name="extension">
<br><h2><input type="submit" name="action" value="Delete Extension">
<br></h2>
<h3>
Main Menu
</h3>
</form>
</center>
I hope U got it :) Enjoy..

Executing PHP Function When a Form Submit is Clicked

I am having trouble understanding handling variables that are passed through pages when a form submit button is clicked. Basically i have a text area where a user writes an sql query. Then clicks submit. Then on the same page (x.php) , i have to display the results in a table. I figured, when the user clicks the button, i call a function that connects to the database, then runs the query, and outputs the result in a table. The code i have below is a mock, and isnt quite working.But above is essentially what i am trying to do.
In my code, I call the page, and check to see if the proper submit button has been clicked, is that how i am suppose to do it?
Also, I am trying to post the metadata in the code below, but how does the table replace what is already on the page?
<html>
<head>
<title>CNT 4714 - Project Five Database Client</title>
</head>
<body style="background-color:white">
<center>
<h1 style="color:red">CNT 4714 - Project Five Database Client</h1>
<hr>
<div style="float:left; text-align:left;padding-right:80px; padding-left:80px; ">
<font color="yellow">
<?php
?>
Welcome Back!<br>
<?php echo $_POST["user"];?>
</font>
</div>
<font color="yellow">
<div style="float:left; text-align:left">
<center>
<h2 style="color:green">Enter Query</h2><br><br>
Please enter a valid SQL Query or update statement. You may also just press<br>
"Submit Query" to run a defualt query against the database!
<form action="" id="sql" method="post">
<br>
<textarea rows="10" cols="50" name="query" form="sql">Enter text here...</textarea><br><br>
<input type="submit" name="submit" color="red">
<input type="submit" name="" color="red" value="Submit Update">
</form>
<?php
if(isset($_POST['submit'])){
echo "hello";
query(); //here goes the function call
}
function query()
{
echo "hello";
$conn = mysqli_connect("localhost:3306", "root", "*******", "project4");
$query = $_POST["query"];
$result = mysqli_query($conn, $query);
$metadata = mysqli_fetch_fields($result);
print("<tr>");
for($i=0; $i<count($metadata);$i++){
print("<tr");
printf("%s",$metadata[$i]->name);
print("</tr>");
}
}
?>
</center>
</div>
</font>
</center>
</body>
</html>
You are trying to get the values of the global variable $_POST while you are posing it to $_GET. The way to fix this is assigning the method into your form element.
Example:
<form id="sql" action="" method="POST">
There are many ways for checking or the form is submitted, one of this ways (the one I am always using) is checking or the $_SERVER['REQUEST_METHOD'] is equal to "POST". This way you can tell the different between a GET, POST, or PUT request.
Example:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['sql']))
{
....
}
}
If you're using $_POST, your form request method should be POST.
<form action="" id="sql" method="post">
Otherwise, it will submit it with a GET request by default.
In that case, you will have to access the variable using $_GET instead.

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

Categories