Good evening, I am currently working on the website where there are two entities students and admins. I am attempting to have the admins have the ability to view a specific student's detail page.
I am having difficulties while attempting to have two sessions running at the same time (one would be the logged in admin, and two would be the "selected student's id" which would be saved when selected from a drop down form: and will be redirected to a "Details" page. Here is where the student information will be populated.). Any ideas into the proper way to do this would be greatly appreciated.
(I am currently thinking of adding a table to my sql and having it populated by Admin_ID as a FK student_ID as a FK, and AD_Select_ID Primary key )
i hope there is a more simple way. please advise.
thank you
Retrieve admin name
if(isset($_SESSION['username']) && isset($_SESSION['ad_loggedin'])) {
$q_auser = "SELECT fName FROM admins WHERE a_id = '$_SESSION[a_id]'";
$r_auser = mysqli_query($dbc, $q_auser);
$auser_data = mysqli_fetch_assoc($r_auser);
}
Retrieve user data
$q_users = "SELECT s_id, fName, lName, dob, email, gender, classification FROM students ORDER BY s_id ASC";
$r_users = mysqli_query($dbc, $q_users);
$user_data = mysqli_fetch_assoc($r_users);
Gather student ID & redirect to profile view
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['profile'])) {
#no profile selected
if($_POST['user'] == "0") {
header('Location: index.php');
} else {
$_SESSION['st_id'] = $_POST['user'];
header('Location: profile.php');
}
}
body post statement:
<label for="users"><h4>Select A User:</h4></label>
<select name="user" class="form-control" id="user" style="width:40%;">
<option value="0"> </option>
<?php
while ($user_data = mysqli_fetch_array($r_users)) {
echo '<option value="'.$user_data["id"].'">' .$user_data["s_id"]. " -> " .$user_data["lName"]. ", ".$user_data["fName"]. '</option>';
}
?>
</select>
<br />
<button type="submit" class="btn btn-primary" name="profile">View Profile</button>
You only ever need to have one session at a time. You can have that session store all the data, such as the actual user and the users being emulated. Whenever your PHP is trying to figure out who the user is, have it check the emulated user data as well. If you want more details, you'll need to give more details about your code.
Related
I'm doing a school project - a website with students performances in various sports. I have three tables:
TABLE1 - "students"
id (primary key)
class
firstname
lastname
TABLE2 - "sports"
sport_id (primary key)
sportname
TABLE3 - "performances"
performance_id (primary key)
sport_id (foreign key - sports.sport_id)
student_id (foreign key - students.id)
value
I want to make a form that adds data into the third table.
That form should include:
class
firstname
lastname
sportname
value
...but I have no idea how to achieve this.
I could just create a form where user user adds value and then copy-pastes sport_id and student_id from tables below it, but that's unpractical.
I've been searching the internet for a while, but I haven't found any solution to this and if I did, it was only for one foreign key.
Does anyone know how to do this? If so, I would highly appreciate it! :)
EDIT: I should've mentioned that tables "students" and "sports" already have all the data in them, I just need to insert new performances using that data.
Since the data is already in the tables for students and sports, this information can be queried with some select statements in order to populate some HTML dropdowns. The advantage of using the select queries and the dropdowns is that value of the options can be set to the database ID while showing the user the human-readable text. Then, the page just needs to monitor for the form's submission and insert the IDs from the dropdowns along with the performance metric. I have not tested the code below, but here is a quicky example of how that might work.
Note: I like the PDO interface for preparing SQL queries in order to prevent injection attacks.
<?php
$user = 'user';
$password = 'password';
$con = new PDO('mysql:dbname=dbname;host=127.0.0.1;chartset=urf8', $user, $password);
$student_stmt = $con->prepare('select * from students');
$student_stmt->execute();
$sport_stmt = $con->prepare('select * from sports');
$sport_stmt->execute();
if (isset($_GET['student']) && isset($_GET['sport']) && isset($_GET['value'])) {
$student = $_GET['student'];
$sport = $_GET['sport'];
$value = $_GET['value'];
$insert_stmt = $con->prepare('insert into preformances (sport_id, student_id, value) values (:sport_id, :student_id, :value)');
$insert_stmt->bindParam(':sport_id', $sport);
$insert_stmt->bindParam(':student_id', $student);
$insert_stmt->bindParam(':value', $value);
$insert_stmt->execute();
}
?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="self.php" method="get">
Student:
<select name="student">
<?php while ($row = $student_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['firstname'] . " " . $row['lastname']; ?></option>
<?php } ?>
</select>
Sport:
<select name="sport">
<?php while ($row = $sport_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['sport_id']; ?>"><?php echo "$row['sportname']"; ?></option>
<?php } ?>
</select>
Performance: <input name="value" type="text" />
<button type="submit">Submit</button>
</form>
</body>
</html>
Edit:
Made the changes in the code in the suggested comment.
I think all you need to do is to get input values from your form ($variable = $_GET["classinput"];) and then connect to database and write mysqli query with input query for every table.
like this:
$query = mysqli_query($connection, "INSERT INTO STUDENTS(id,class,firstname,lastname) VALUES (null,\"$class\",\"$firstname\",\"$lastname\")");
And do this for all your tables.
I have been having an issue selecting data from my database based on the user id column. I know that I have to make use of PHP sessions to enable each user see their profile when they login, but I haven't been able to work out the code for this.
Here is what I have so far:
<?php session_start(); include 'dpconfig.php'; $id = $_SESSION['uid'] ?>
<?php
$run = mysqli_query($conn,"Select * from user Where first = '$id'");
$row = mysqli_fetch_array($run, MYSQLI_BOTH); {}
$showid = $row[0];
$showfirst = $row[1];
$showlast = $row[2];
echo $showid;
echo $showfirst;
echo $showlast;
?>
If I run the above code I get nothing echoed out, but if I remove the WHERE clause from my SELECT statement, all logged in users see the first column of my database.
I want each user to see their own profile, I learnt that I need to authenticate session, and I am confused. Please help.
Assumptions
I'm assuming your database has three columns, uid (the id of a user, int, primary key, auto_increment), first (the user's first name, varchar) and last (the user's last name, varchar).
I'm also assuming that when the user logs in, $_SESSION["UID"] is set to the value of the id column in their row.
Solution
As far as I can see, your WHERE clause is wrong. You wrote
Select * from user Where first = '$id'
which essentially means "Select everything from the user table where the first name is equal to the currently logged in user's id". I think you meant something more like
SELECT first, last FROM user WHERE uid='$id'
which means "Select the first and last names from the user table where the id is equal to the currently logged in user's id".
Code
I have re-written your PHP file, to make it a bit more readable and clear. You'll need to change the MySQL connection to whatever you were originally using, but apart from that, everything should work fine.
<?php
session_start();
require("dpconfig.php");
$q = "SELECT first, last FROM user WHERE uid='".$_SESSION["UID"]."'";
$r = mysqli_query($conn,$q);
$a = mysqli_fetch_assoc($r);
echo "First Name: ".$a["first"]."<br>";
echo "Last Name:".$a["last"];
?>
Second Question
For your form:
<form method="post" action="update.php">
<input type="text" name="status"><br>
<button>Submit</button>
</form>
For update.php:
<?php
session_start();
require("dpconfig.php");
if (isset($_POST["status"])) {
$q = "UPDATE user SET status='".addslashes($_POST["status"])."' WHERE uid='".$_SESSION["uid"]."'";
mysqli_query($conn,$q);
}
header("Location:./");
?>
I dont know what to do with this. I want to update a record from database. I have header were there, the fullname of the user is displayed once login, and has also a dropdown. One of this dropdown is Account Setting were a user can update his Information. But I dont know what to do since Its my first time working with php. below is my code in displaying the record.
<?php
$session_useraccount_id=$_SESSION['useraccount_id'];
$qry= "SELECT * FROM tblusersaccount where useraccount_id = '$session_useraccount_id'";
$result=mysql_query($qry) or die(mysql_error());
{
$useraccount_id=mysql_result($result,$i,'useraccount_id');
$fname=mysql_result($result,$i,'fname');
$lname=mysql_result($result,$i,'lname');
$email=mysql_result($result,$i,'email');
$password=mysql_result($result,$i,'password');
$useraccountname=mysql_result($result,$i,'useraccountname');
?>
<?php echo "<a style='color: white' href='updateusers.php?update = $useraccount_id'>$fname $lname   ";?>
It gives me the id, and I can display it to other page.
$qry= "SELECT useraccount_id, fname, lname, useraccountname, email, password FROM tblusersaccount";
$result=mysql_query($qry) or die(mysql_error());
{
$useraccount_id=mysql_result($result,$i,'useraccount_id');
$fname=mysql_result($result,$i,'fname');
$lname=mysql_result($result,$i,'lname');
$useraccountname=mysql_result($result,$i,'useraccountname');
$password=mysql_result($result,$i,'password');
}
and below I put this
First Name" required>
and so on.
How can I update my record??
Question not clear, by the way you can provide a button that onCLick, once you collect the account data, executes an update query on server side.
I have a simple drop down menu.
<form method="post" action="index.php">
<select name="mountname">
<option value="white">white</option>
<option value="black">black</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
</select>
<input type="submit" value="Submit Pick" />
to save what is selected I used.
if (!empty($_POST['color'])){
$id = $_SESSION['user_id'];
$color = $_POST['color'];
mysqli_query($mysqli,"UPDATE users SET home_color='".$color."' WHERE id='".$id."'")or die("error == ----> ".mysqli_error());
mysqli_close($mysqli);
header('Location: index.php');
}
saving the color to mysql is no problem.
//update//
the USER table is set up like this.
ID, username,password, first_name, last_name, email,home_color
When a user selects his home color, and then submits it it is saved to the db.
ie 1, Bob, MD5pass, Bob,Smith,Bob#bob.com, Black
2, Joe, MD5pass, Joe,Doe,joe#Doe.com, Green
now i have another table called mount.
mount has color info in it.
this table hold color name, and info.
ID, color_name, color_info
the ID is is an INT with A_I.
Bob Logs in and selects his home color saves it to his profile.
so now when a person goes to bobs profile the will see color info.
how do I make it where it reads profile info and displays info from another table.
something like the code below. I know the code is wrong, but only way i can explain it.
if (black){
mysqli_query($mysqli,"SELECT * FROM mount;
}else{
(green)
As you said, color is saved in user's table. Problem is how to fetch color's data from mount along with user's data..
On Profile Page, you can get details of user with color by ..
$id = $_SESSION['user_id'];
$res = mysqli_query($mysqli,"SELECT * FROM users u, mount c WHERE u.home_color=c.color_name AND u.id='".$id."'")or die("error == ----> ".mysqli_error());
$result = mysqli_fetch_array($res);
mysqli_close($mysqli);
Now, you can manipulate $result as it contains users detail as well as color detail! We are getting data from both tables users and mount by same keys comparision home_color of users and color of mount.
If you saved colors in mount like 'Black', I'm suggesting you to keep same keyword in <select> dropdown, as 'Black' is not equal to 'black'.
Another thing I want to suggest you is, Change your select dropdown to dynamic. Fetch color data from table mount and use it like..
<select name="mountname">
<?php
$res_colors = mysqli_query($mysqli, "SELECT * FROM mount");
$colors = mysqli_fetch_array($res_colors);
foreach($colors as $color){
?>
<option value="<?php echo $color['color']; ?>"><?php echo $color['color']; ?></option>
<?php } ?>
</select>
Best way to use primary key as foreign key, so use ID of mount instead of color for dropdown and saving it to user's table.
I've made a 'like' button for my product pages with this code:
<?php
if('POST' == $_SERVER['REQUEST_METHOD']) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" value = "like"/>
</form>
Works like a charm excpet for one minor problem being that every visit to the page registers a 'like'.
Could someone help explain what i need to chnage/add in order that new 'likes' are only registered when the actual form is submitted?
Thanks
Dan
A better solution rather than submitting the page and the whole page reloading would be to make an AJAX request, this is how Facebook 'likes' work.
This can be achieved using the jQuery JavaScript library.
The general outline would be:-
1) Click button
2) Send AJAX request
3) Update HTML to show button has been clicked and prevent reclicking of button.
<?php
if($_POST['like']) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" value = "like" name='like'/>
</form>
This should work ;-)
<?php
if ($_POST['like']){
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" name="like" value = "like"/>
</form>
First of all - in your sql you have:
`product_id` = '1'
do not use id value as a string:
`product_id` = 1
About your problem:
Add another condition:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
if ( !empty($_POST['submitType']) && ( $_POST['submitType'] == 'like' ) ) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
}
and in html:
<input type = "submit" name="submitType" value = "like"/>
Sounds like some kind of old question, but I wonder why noone has said, that op's approach doesn't sound quite right. You try to just count likes (set likes=likes+1). It has many disadvantages:
You miss information, who gave the like. Thus you won't be able to reconstruct the whole picture
Users won't be able to "undo" likes (as you don't record who liked the post)
In case of many concurrent likes I feel like you'd get some kind of data race or a long delays, because MySQL would need to process every request on a single field in order.
Much better idea is to create separate table in the DB named "product_likes" with columns like product_id, user_id, date. Of course, product id and user id should be unique together.
Thus you'll always know the full picture and will be able to see who liked the product. Even if accidentally you'll issue the second like from the same user about the same product, it won't be stored due to db constraints.
Also it will be possible to extend it to i.e. emotions-reactions, just by adding new column like "like_type" and updating the constraint correspondingly.