Can't update some fields in user profile - php

I'm relatively new to PHP and MySQL, I am trying to learn how to create a user profile page that allows users to edit their information. The issue I am having is that some fields do not change, such as the username, email, and contact field. However, I am able to change the name field alone but not with the other fields. I don't get redirected back and no errors pop up, so I am unsure as to how to fix the issue. Below is my code.
<?php
include 'db_conn.php';
session_start();
if (!isset($_SESSION['userid'])){
header("Location:login.php");
}
$select = mysqli_query($con, "SELECT * FROM user WHERE userid = $_SESSION[userid]") or die('query failed');
if(mysqli_num_rows($select) > 0){
$fetch = mysqli_fetch_assoc($select);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css#2/out/water.css">
</head>
<body>
<form action="update-profile-check.php" method="post">
<h2>PROFILE</h2>
<?php if (isset($_GET['error'])) { ?>
<p class="error"><?php echo $_GET['error']; ?></p>
<?php } ?>
<?php if (isset($_GET['success'])) { ?>
<p class="success"><?php echo $_GET['success']; ?></p>
<?php } ?>
<label>User Name</label>
<input type="text"
name="uname"
placeholder="User Name"
value="<?php echo $fetch['username']; ?>"><br>
<label>Name</label>
<input type="text"
name="name"
placeholder="Name"
value="<?php echo $fetch['name']; ?>"><br>
<label>Email</label>
<input type="text"
name="email"
placeholder="Email"
value="<?php echo $fetch['email']; ?>"><br>
<label>Contact</label>
<input type="text"
name="contact"
placeholder="Contact"
value="<?php echo $fetch['contact']; ?>"><br>
<button type="submit">Update Profile</button>
go back
change password
</form>
</body>
</html>
<?php
session_start();
include "db_conn.php";
$select = mysqli_query($con, "SELECT * FROM user WHERE userid = $_SESSION[userid]") or die('query failed');
if(mysqli_num_rows($select) > 0){
$fetch = mysqli_fetch_assoc($select);
}
$oguname = $fetch['username'];
$ogemail = $fetch['email'];
$ogcontact = $fetch['contact'];
$ogname = $fetch['name'];
$userid = $_SESSION["userid"];
if (isset($_POST['uname']) || isset($_POST['name']) || isset($_POST['email']) || isset($_POST['contact'])) {
function validate($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$uname = validate($_POST['uname']);
$name = validate($_POST['name']);
$email = validate($_POST['email']);
$contact = validate($_POST['contact']);
$user_data = 'uname='. $uname. '&name='. $name. '&email='. $email. '&contact='. $contact;
if (empty($uname)) {
header("Location: update-profile.php?error=User Name is required&$user_data");
exit();
}
else if(empty($name)){
header("Location: update-profile.php?error=Name is required&$user_data");
exit();
}
else if(empty($email)){
header("Location: update-profile.php?error=Email is required&$user_data");
exit();
}
else if(empty($contact)){
header("Location: update-profile.php?error=Contact is required&$user_data");
exit();
}
else if(!preg_match("/^([a-zA-Z-' ]+)$/", $name)){
header("Location:update-profile.php?error=Name can only contain letters&$user_data");
exit();
}
else if (strlen($name) > 51){
header("Location:update-profile.php?error=Name is too long&$user_data");
exit();
}
else if ($oguname !== $_POST['uname']){
$sql = "SELECT * FROM user WHERE username='$uname' ";
$result = mysqli_query($con, $sql);
if (!preg_match("/^[A-Za-z][A-Za-z0-9]{2,16}$/", $uname)){
header("Location: update-profile.php?error=Username can only contain letters (a-z) and numbers (0-9) and must have a minimum of three characters and maximum of 15 characters&$user_data");
exit();
}
if (mysqli_num_rows($result) > 0) {
header("Location: update-profile.php?error=That username is already taken&$user_data");
exit();
}
}
else if($ogemail !== $_POST['email']){
$sql2 = "SELECT * FROM user WHERE email='$email' ";
$result2 = mysqli_query($con, $sql2);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: update-profile.php?error=Invalid Email&$user_data");
exit();
}
if (mysqli_num_rows($result2) > 0) {
header("Location: update-profile.php?error=That email has already been used!&$user_data");
exit();
}
}
else if ($ogcontact !== $_POST['contact']){
$sql3 = "SELECT * FROM user WHERE contact='$contact' ";
$result3 = mysqli_query($con, $sql3);
if(!preg_match("/^[89]\d{7}$/", $contact)){
header("Location: update-profile.php?error=Invalid Phone Number&$user_data");
exit();
}
if (mysqli_num_rows($result3) > 0) {
header("Location: update-profile.php?error=Phone number has already been used&$user_data");
exit();
}
}
else{
$sql4= "UPDATE user SET username = ?, email = ?, contact = ?, name = ? WHERE userid = ?; ";
$query = $con->prepare($sql4);
$query->bind_param("ssisi" ,$uname, $email, $contact, $name, $userid);
if ($query -> execute()){
header("Location: update-profile.php?success=Succesfully updated");
exit();
}else {
header("Location: update-profile.php?error=unknown error occurred&$user_data");
exit();
}
}
}
else{
header("Location:update-profile.php");
exit();
}
I am not sure as to why only the name field is able to be changed but the rest just redirects and changes nothing. Also, I am trying to incorporate more prepared statements to prevent SQL injections later on.

Solved this issue by removing the else statement with the $sql4.

Related

Change signup page echo message based on if statement from different page

I am practicing PHP and database creation and would like to change my message based on errors from the input. I can't figure out how to pass the changed messaged back and would appreciate any help given.
This is my sign up page
<main>
<h1>Signup<h1>
<h3>
<?php
echo $errorMsg;
?>
<h3>
<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd_repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Submit</button>
<form>
</main>
This is my processing page
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$Name = $_POST['uid'];
$Email= $_POST['mail'];
$Password = $_POST['pwd'];
$PasswordRepeat = $_POST['pwd_repeat'];
if(empty($Name) || empty($Email) || empty($Password) || empty($PasswordRepeat)){
header("Location: ../signup.php?error=emptyfields=1"); //Check if any field is empty
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $Name)){
header("Location: ../signup.php?error=invalidamil&uid"); //Check if username and email is valid input
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidamil&uid=".$Name); //Check if email is valid input
exit();
}
else if($Password !== $PasswordRepeat){
header("Location: ../signup.php?error=passwordCheck&uid=".$Name."&mail=".$Email); // Check if passwords don't match
exit();
}
$sql2 = "SELECT UserName FROM dbo.MainTable WHERE UserName = ?";
$params2 = array($Name, SQLSRV_PARAM_IN);
$stmt2 = sqlsrv_query($conn, $sql2, $params2);
if($stmt2 === false)
{
die(print_r(sqlsrv_errors(), true));
exit();
}
$row_count = sqlsrv_num_rows($stmt2);
if($row_count != 0)
{
$_SESSION['errMsg'] = "Error retrieving username";
header("location: ../register.php");
exit();
}
else if($row_count > 0)
{
$_SESSION['errMsg'] = "Username is already used";
header("Location: ../signup.php?error=UserNameTaken&uid");
exit();
}
else{
$sql = "INSERT INTO dbo.MainTable(UserName,Email,UserPassword)
VALUES (?,?,?)";
$Password = PASSWORD_HASH($_POST['pwd'], PASSWORD_DEFAULT); //Password hashing
$stmt = sqlsrv_query($conn, $sql,array(#$Name,#$Email,#$Password));
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}else{
$_SESSION['errMsg'] = "Registration completed!";
header("Location: ../signup.php?signup=COMPLETE");
exit();
}
}
I am not sure where to put a change message variable here because I couldn't get it work in the if statements.
You are providing the error message as an url paramenter, so you can access it with php $_GET
<h3>
<?php
echo $_GET['error'];
?>
<h3>

Login system with password_hash [duplicate]

This question already has answers here:
PHP password_hash(), password_verify()
(2 answers)
Closed 3 years ago.
I am trying to login users that are added by an admin, but when I press login, nothing happens, just a blank page with the header login.php.
Here is the code I use to add users:
<?php
include "connection.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Add students</title>
<link rel="stylesheet" type="text/css" href="boosttrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="adduser.php" method="POST">
<div>
<h2>
Username will be generated automatically
</h2>
<br/>
<label>Password</label>
<input type="password" name="s_password" class="form-control" placeholder="Enter new passowrd">
<br/>
<label>Name</label>
<input type="text" name="s_name" class="form-control" placeholder="Enter name">
<br/>
<label>Surname</label>
<input type="text" name="s_surname" class="form-control" placeholder="Enter surname">
<br/>
<label>Date of birth</label>
<input type="date" name="s_dob" class="form-control" placeholder="Enter Date of birth">
<br/>
<label>Year group</label>
<select name ="s_yeargroup">
<option selected = "true" disabled="disabled"> Select one from below...</option>
<option value=1 >7</option>
<option value=2> 8</option>
<option value=3> 9</option>
<option value=4> 10</option>
<option value=5> 11</option>
</select>
<br/>
<button type="sumbit" name="btnAddUser" class="float" value ="Login">Create New User</button>
</div>
</form>
Logout
</body>
<?php
if(isset($_POST["btnAddUser"])){
$hashed_password = password_hash($_POST['s_password'], PASSWORD_DEFAULT);
$name = $_POST["s_name"];
$surname = $_POST["s_surname"];
$dob = $_POST["s_dob"];
$yeargroup = $_POST["s_yeargroup"];
$usernamenew = substr($name, 0, 1);
$usernamenew1 = substr($surname, 0, 4);
$usernamenew3= $usernamenew.$usernamenew1;
$sql = "INSERT INTO tbluser (Username, Password, Role) VALUES ('$usernamenew3', '$hashed_password', 'Student')";
if(!mysqli_query($conn,$sql))
{
echo "Error with Username or password";
}
else
{
echo "Username and password created successfully. The username is ".$usernamenew3.".";
}
$sql4= "SELECT ID FROM tbluser WHERE Username = '$usernamenew3'";
$result1= mysqli_query($conn,$sql4);
$row= mysqli_fetch_assoc($result1);
$userid=$row['ID'];
$sql1 = "INSERT INTO student (name, surname, dob, yeargroup_id, tbluser_ID) VALUES ('$name','$surname','$dob','$yeargroup','$userid')";
if(!mysqli_query($conn,$sql1))
{
echo "Error with Student info";
}
else
{
echo " \r\nStudent has been added successfully.";
}
}
?>
And here is my code that I use to login users
<?php
session_start();
require_once "connection.php";
$message = "";
$role = "";
if(isset($_POST["btnLogin"]))
{
$password = $_POST["password"];
$stmt=$conn->prepare("SELECT Username, Password FROM tbluser WHERE Username = ? ");
$stmt-> bind_param("s",$_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
if(password_verify($password, $row["Password"]))
{
if($row["Role"] == "Admin")
{
$_SESSION['AdminUser'] = $row["Username"];
$_SESSION['adminid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: admin/admin.php');
}
elseif($row["Role"] == "Teacher")
{
$_SESSION['ProfUser'] = $row["Username"];
$_SESSION['teacherid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: teacher/prof.php');
}
elseif($row["Role"] == "Student")
{
$_SESSION['StudentUser'] = $row["Username"];
$_SESSION['studentid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: student/student.php');
}
else
echo "Role is not recognised";
}
}
}
}
If anyone could find my mistake, I would appreciate it. Thank you
My database in case you need it.
Your use of password_hash() and password_verify() is fine.
You're only selecting the Username and Password columns from the table. So $row["Role"] won't be set and none of the if conditions will succeed. You should be getting the error Role is not recognized as a result.
Change it to:
$stmt=$conn->prepare("SELECT Username, Password, Role, ID FROM tbluser WHERE Username = ? ");
Also, add else statements so you know which if condition is failing when the login fails.
<?php
if(isset($_POST["btnLogin"]))
{
$password = $_POST["password"];
$stmt=$conn->prepare("SELECT Username, Password FROM tbluser WHERE Username = ? ");
$stmt-> bind_param("s",$_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if(password_verify($password, $row["Password"]))
{
if($row["Role"] == "Admin")
{
$_SESSION['AdminUser'] = $row["Username"];
$_SESSION['adminid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: admin/admin.php');
}
elseif($row["Role"] == "Teacher")
{
$_SESSION['ProfUser'] = $row["Username"];
$_SESSION['teacherid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: teacher/prof.php');
}
elseif($row["Role"] == "Student")
{
$_SESSION['StudentUser'] = $row["Username"];
$_SESSION['studentid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: student/student.php');
}
else
echo "Role is not recognised";
} else {
echo "Password incorrect";
}
} else {
echo "Username not found";
}
} else {
echo "Form not submitted correctly";
}
You don't need a while loop when fetching the row, since usernames are unique; there's just one row.
From the password_hash documentation, password_hash with PASSWORD_BCRYPT, produces a string 60 characters long and other algorithms might produce even longer. Your Password field in the database is only 45 characters.
As per recommendation from the documentation, you should increase the field size to 255.

PHP/SQL StoringThe Name Of The Currently Logged In User Upon Form Completion

Once users are logged into my website, they can fill out a form which has two fields, "project name" and "project description".
I need help storing the username of the person who filled that form out.
For example, if I was to be logged in as Admin and filled the form out, in the database it should show the username Admin next to the form information.
Help is much appreciated and thank you in advance!
The form DB:
Database name: formsystem
Table name: form
Column I want to save the usernames to: form_user
My Code (groupForm.php):
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="./css/form.css">
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<nav>
<div class="main-wrapper">
<div id="branding">
<li><h1><span>ProjectNet</span></li>
</div>
<div class="nav-login">
<?php
if (isset($_SESSION['u_id'])) {
echo '<form action="includes/logout.inc.php" method="POST">
<button type="submit" name="submit">Logout</button>
</form>';
} else {
echo '<form action="includes/login.inc.php" method="POST">
<input type="text" name="uid" placeholder="Username/Email">
<input type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Login</button>
</form>
Sign up';
}
?>
</div>
</nav>
</header>
<section id="showcase1">
<div class="container">
<form id="contact" action="includes/form_process.php" method="POST">
<h3>Creating a Group</h3>
<h4>Please fill out the sections below.</h4>
<fieldset>
<input placeholder="Project title" type="text" name="name">
</fieldset>
<fieldset>
<textarea placeholder="Description of the project...." type="text" name="message" ></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit">Create</button>
</fieldset>
</form>
</div>
</section>
</body>
</html>
Backend Code (form_process.php):
<?php
session_start();
if (isset($_POST['submit'])) {
function fetch_user_info($u_id){
$u_id = (int)$u_id;
$sql = "SELECT `user_uid` AS `username` FROM `users` WHERE `user_id` = {$u_id}";
$result = mysql_query($sql);
return mysql_fetch_assoc($result);
}
include_once 'formDatabaseConnection.php';
$name = mysqli_real_escape_string($conn, $_POST['name']);
$message = mysqli_real_escape_string($conn, $_POST['message']);
//Check for empty fields
if (empty($name) || empty($message)) {
header("Location: ../groupForm.php?signup=empty");
exit();
} else {
//Insert the user into the database
$sql = "INSERT INTO form (form_user, form_name, form_description) VALUES ('$u_id', '$name', '$message');";
mysqli_query($conn, $sql);
header("Location: ../findGroup.php");
exit();
}
} else {
header("Location: ../groupForm.php");
exit();
}
UPDATES:
Login code(login.inc.php):
<?php
session_start();
if (isset($_POST['submit'])) {
include 'dbh.inc.php';
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check if inputs are empty
if (empty($uid) || empty($pwd)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid' OR user_email='$uid'";
$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
$hashedPwdCheck = password_verify($pwd, $row['user_pwd']);
if ($hashedPwdCheck == false) {
header("Location: ../index.php?login=error");
exit();
} elseif ($hashedPwdCheck == true) {
//log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_first'] = $row['user_first'];
$_SESSION['u_last'] = $row['user_last'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_uid'] = $row['user_uid'];
header("Location: ../homepage.php");
exit();
}
}
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
When a user logging in your system, store that user's ID & user name in session & retrieve that user name when you want to save it & replace your form_user value with that session value. Check below code for more clarification.
$username = $_SESSION['u_first']. ' '.$_SESSION['u_last'];
$sql = "INSERT INTO form (form_user, form_name, form_description) VALUES ($username, $name, $message)";

Php/Mysql login authentication

I am unable to authenticate using Php/mysql, using the following method. I used a form in order to login. Please check the following and help me out?
form.php
<html>
<body>
<h2>Authentication</h2>
<form action="login.php" method="post">
<label>Userid :</label>
<input type="text" id="userid" name="userid" >
<label>Password :</label>
<input type="password" id="password" name="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</body>
</html>
login.php
<?php
$message="";
if(count($_POST)>0) {
mysql_connect("localhost", "root", "kami123")or
die(mysql_error());
mysql_select_db("ccmsdb") or die(mysql_error());
$result = mysql_query("SELECT *FROM client WHERE
userid='" . $_POST["userid"] . "' AND
password = '". $_POST["password"]."'");
$count = mysql_num_rows($result);
if($count==0) {
$message = "Invalid Username or Password!";
} else {
$message = "You are successfully authenticated!";
}
}
?>
Besides what's already mentioned in the comments, you are missing a space in the query:
SELECT *FROM client WHERE
should be
SELECT * FROM client WHERE
Why don't you try PDO? MySQL functions are deprecated.
$err="";
(isset($_POST['email'], $_POST['pass'])) {
$email = $_POST['email'];
$pass = $_POST['pass'];
if(!empty($email) && !empty($pass)) {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
$err = 'Invalid email format.';
}
$dbc = new PDO('mysql:host=YOUR HOST;dbname=YOUR DBNAME', 'YOUR USERNAME', 'YOUR PASSWORD');
$stmt = $dbc->prepare("SELECT id, name, pass FROM client WHERE email =:email LIMIT 1");
$stmt -> bindValue(':email', $email);
$stmt -> execute();
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ){
if(password_verify($pass, $row['pass'])) {
//Logged In
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
header('Location:logged_in_user_page.php');
... bla bla ...
}else {
// Not Logged In
header('Location:not_logged_in_user_page.php');
}
}
}else {
$err = 'You have to provide an email and a password!';
}
}

Html/php/mysql forms are not submitting and redirecting issue

i'm working on a dashboard for my users. I set it up by ranks and each rank can do there own thing. Now, I have three problems. One and two are about forms and another is about a redirection problem. These forms are not submitting into the database and I don't know why. The two forms are below. The third problem is redirecting. Since the system is setup by ranks I don't want ranks accessing other ranks dashboards. Its not redirecting the other ranks away from there dashboard as its all one login and when those ranks login it redirects them to there correct dashboard, but if say a partner goes to the admin dashboard, it lets them in which I don't want. Also I forgot to mention that when the user is logged in, it lets them back to the login page if they go to the login url which I don't want, I want it to redirect them to there dashboard. The forms are below.
First Form:
<?php
$id = $_GET['id'];
$result = $db->query("SELECT * FROM users WHERE Id = '.$id.'");
if(isset($_POST['submit']))
{
$username1 = $_POST['username'];
$email1 = $_POST['email'];
$password1 = $_POST['password'];
$f_name = $_POST['f_name'];
$l_name = $_POST['l_name'];
$rank1 = $_POST['rank'];
$skype1 = $_POST['skype'];
$db->query("UPDATE users SET (Email, Username, FName, LName, Rank, SkypeID) VALUES(''.$email1.'', ''.$username1.'', ''.$f_name.'', ''.$l_name.'', ''.$rank1.'', ''.$skype1.'') WHERE Id = ".$id."");
}
?>
<?php
$id = $_GET['id'];
$result = $db->query("SELECT * FROM users WHERE id='$id'");
while($row = $result->fetch_assoc())
{
$username = $row['Username'];
$email = $row['Email'];
$fname = $row['FName'];
$lname = $row['LName'];
$rank = $row['Rank'];
$skype = $row['SkypeID'];
}
?>
<form method="POST">
Username: <input type="text" name="username" value="<?php echo ($username); ?>"><br>
Email: <input type="email" name="email" value="<?php echo ($email);?>"><br>
Passowrd: <input type="password" name="password"><br>
First Name: <input type="text" name="f_name" value="<?php echo ($fname);?>"><br>
Last Name: <input type="text" name="l_name" value="<?php echo($lname); ?>"><br>
Rank: <input type="text" name="rank" value="<?php echo ($rank); ?>"><br>
Skype: <input type="text" name="rank" value="<?php echo ($skype); ?>">
<button type="submit" name="submit">Update User</button>
</form>
Second Form:
<?php
if(isset($_POST['submit']))
{
$c_name = $_POST['c_name'];
$v_link = $_POST['v_link'];
$v_title = $_POST['v_title'];
$v_desc = $_POST['v_desc'];
$v_tags = $_POST['v_tags'];
$m_sources = $_POST['m_sources'];
$s_requests = $_POST['s_requests'];
if(empty($c_name) or empty($v_link) or empty($v_title) or empty($v_title) or empty($v_desc) or empty($v_tags))
{
echo 'You must fill in the first 5 fields.';
}
else
{
$getRank = $db->query("SELECT * FROM users WHERE username = ".$_SESSION['username']."");
while ($row = $getRank->fetch_assoc($getRank))
{
$usename = $row['username'];
$rank = $row['rank'];
}
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES (''.$username.'', ''.$rank.'', ''.$c_name.'', ''.$v_link.'', ''.$v_title.'', ''.$v_desc.'', ''.$v_tags.'', ''.$m_sources.'', ''.$s_requests.'')");
echo 'Form submitted successfully.';
}
}
?>
<form method="POST">
Channel name: <input type="text" name="c_name" required>*<br>
Video Link: <input type="text" name="v_link" required>*<br>
Video Title: <input type="text" name="v_title" required>*<br>
Video Description: <input type="text" name="v_desc" required>*<br>
Video Tags: <input type="text" name="v_tags" required>*<br>
Music Sources: <input type="text" name="m_sources"><br>
Special Requests: <input type="text" name="s_requests"><br>
<button type="submit" name="submit">Submit</button><br>
</form>
Now, heres the code I use to redirect a user away from the dashboards if its not there dashboard. It redirects not logged in users, but not like other users. Its supposed to only allow admins in.
<?php session_start();
if(isset($_SESSION['admin']))
{
$_SESSION['username'];
} else {
header("location: ../index.php");
} ?>
Now, heres the login script. I want it to redirect the ranks to there dashboard if they're logged in, I don't know how to implant this.
<?php
require 'core/config.php';
if(isset($_POST['submit']))
{
$username = $db->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
if(empty($username) or empty($password))
{
echo 'You must fill in both boxes!';
} else {
$query = $db->query("SELECT * FROM users WHERE username = '".$username."'");
while($row = $query->fetch_assoc())
{
$dbpassword = $row['Password'];
}
if($password !== $dbpassword)
{
echo 'Password was incorrect.';
} else {
$query1 = $db->query("SELECT * FROM users WHERE username='".$username."'");
while($rows = $query1->fetch_assoc())
{
$rank = $rows['Rank'];
}
if($rank === 'admin')
{
$_SESSION['admin'] = '1';
$_SESSION['username'] = $username;
echo '<script>window.location="management/index.php";</script>';
}
elseif ($rank === 'partner')
{
$_SESSION['partner'] = '1';
$_SESSION['username'] = $username;
echo '<script>window.location="partner/index.php";</script>';
}
elseif ($rank === 'trainee')
{
$_SESSION['trainee'] = '1';
$_SESSION['username'] = $username;
echo '<script>window.location="trainee/index.php";</script>';
}
else
{
echo 'Account not found.';
}
}
}
}
?>
try this in your login script:
<?php
require 'core/config.php';
//assuming that you have already start your session at the very top
if(isset($_POST['submit']))
{
$username = $db->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
if(empty($username) or empty($password))
{
echo 'You must fill in both boxes!';
} else {
$query = $db->query("SELECT * FROM users WHERE username = '".$username."'");
while($row = $query->fetch_assoc())
{
$dbpassword = $row['Password'];
}
if($password !== $dbpassword)
{
echo 'Password was incorrect.';
} else {
$query1 = $db->query("SELECT * FROM users WHERE username='".$username."'");
while($rows = $query1->fetch_assoc())
{
$rank = $rows['Rank'];
}
if($rank === 'admin')
{
$_SESSION['rank'] = $rank;
$_SESSION['username'] = $username;
echo '<script>window.location="management/index.php";</script>';
}
else if ($rank === 'partner')
{
$_SESSION['rank'] = $rank;
$_SESSION['username'] = $username;
echo '<script>window.location="partner/index.php";</script>';
}
else if ($rank === 'trainee')
{
$_SESSION['rank'] = $rank;
$_SESSION['username'] = $username;
echo '<script>window.location="trainee/index.php";</script>';
}
else
{
echo 'Account not found.';
}
}
}
}
?>
in your management/index.php or in the page where supposed to only allow admins in.
<?php session_start();
if(isset($_SESSION['rank']) and $_SESSION['rank'] == "admin")
{
$_SESSION['username'];
} else {
header("location: ../index.php");
} ?>
and with you saving, you just maybe forget the right quotations:
<?php
if(isset($_POST['submit']))
{
$c_name = $_POST['c_name'];
$v_link = $_POST['v_link'];
$v_title = $_POST['v_title'];
$v_desc = $_POST['v_desc'];
$v_tags = $_POST['v_tags'];
$m_sources = $_POST['m_sources'];
$s_requests = $_POST['s_requests'];
if(empty($c_name) or empty($v_link) or empty($v_title) or empty($v_title) or empty($v_desc) or empty($v_tags))
{
echo 'You must fill in the first 5 fields.';
}
else
{
$getRank = $db->query("SELECT * FROM users WHERE username = '$_SESSION[username]'");
while ($row = $getRank->fetch_assoc($getRank))
{
$usename = $row['username'];
$rank = $row['rank'];
}
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES ('$username', '$rank', '$c_name', '$v_link', '$v_title', '$v_desc', '$v_tags', '$m_sources', '$s_requests')");
echo 'Form submitted successfully.';
}
}
?>

Categories