Load disparate views based on user name using PHP - javascript

I have created a student and teacher feedback system using PHP and MySQL. Students and lecturers should be shown a separate view once they login. A students username takes the form of B******** and a lecturers' username takes the form of E********. I'm thinking is there a way to take the user inputed username and to truncate it and match the B or E and then serve up the relevant PHP view for the given user or is there a better way to achieve what I'm after. I'm relatively new to PHP so any help would be much appreciated.

Below would be my approach:
In the database, make a "userType" column that indicates whether a username belongs to a student or a teacher.
User submits their login details. You find a match, check the "userType" column and display a view accordingly.
Here's a very basic example with code
$sql = $this->db->query("
SELECT userType
FROM userTable
WHERE userName = //Username typed in by the user
AND password = //Password typed in by the user
");
$result = $sql->fetchAll();
if($result[0][0] == "student") include_once "student.php";
if($result[0][0] == "teacher") include_once "teacher.php";
else echo "User does not exist";

You can easily get the first character of a string with array access syntax [], string access syntax {}, and a variety of other methods.
if ("B" == $name[0]) {
// show student page
}
else {
// show instructor page
}

if ( $username[0] == 'E' )
{
// It's a teacher
} else if ( $username[0] == 'B' )
{
// It's a student
} else {
// Username is invalid
}

Related

Alerting users on website through ajax

I'm attempting to make a notification system that notifies users when they are assigned to a ticket, or when a new ticket is added to the database.
The system itself, that I already have, works except that it only sends the notification to the first user who receives the ajax request. Is there any way to make it so that everyone who is suppose to receive the notification, actually receives the notification?
My code:
javascript:
function checkUpdates()
{
$.ajax({
type: "POST",
url: 'ajax/checkDB.php', // a webservice or other URL that queries the database
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log('Connected and executed PHP page... '+data);
if (data.hasChanged == "true") {
playSound('img/notif2');
notifyAdmin();
console.log('Updated Tickets Page...');
$("#contents").load("dynamic/tickets.php");
$("#contents").fadeTo("fast", 1);
}
if (data.newAssigned == "true") {
playSound('img/notif2');
notifyUser();
console.log('Updated Tickets Page...');
$("#contents").load("dynamic/tickets.php");
$("#contents").fadeTo("fast", 1);
}
}
});
}
$(document).ready(function() {
setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds
});
My php script (checkDB.php):
<?php
include("../static/config.php");
session_start();
header("Content-Type: text/json");
$result = mysqli_query($con,"SELECT notify FROM tickets WHERE notify='0'");
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0) {
$hasChanged = 'true';
mysqli_query($con,"UPDATE tickets SET notify='1' WHERE notify='0'");
} else {
$hasChanged = 'false';
}
$result2 = mysqli_query($con,"SELECT notify,Assigned FROM tickets WHERE Completeness='1' AND notify='1'");
$row_cnt2 = mysqli_num_rows($result2);
if($row_cnt2 > 0) {
while($row2 = mysqli_fetch_array($result2))
{
if(strcmp($_SESSION['Name'],$row2['Assigned']) == 0) {
$newAssigned = 'true';
} else {
$newAssigned = 'false';
}
}
mysqli_query($con,"UPDATE tickets SET notify='2' WHERE Completeness='1' AND notify='1'");
} else {
$newAssigned = 'false';
}
echo json_encode(array('newAssigned' => $newAssigned, 'hasChanged' => $hasChanged));
?>
Here is a rundown of my exact intentions:
User logs into system, and is given administrative rights if granted.
User loads the tickets page, which lists all the tickets along with this javascript that I gave you
the javascript loads checkDB.php every 3 seconds, basically running a check against the database for a 'notify' value of 0, and if at least 1 exists, is updated in the database to '1' and is returned as true to the ajax call - which sends out notifications.
Again this works for the 1st user who is loaded into the page, but after that, obviously there are no more 'notify=0' in the database as they have already been updated, so they are not shown the notification.
It was requested that I share my database structures.
tickets:
UniqueID - Unique ID per ticket (always unique)
Requester - Whoever submitted the ticket.
Problem - Description of the given issue.
Assigned - User who is assigned to the ticket.
Completeness - The level of completeness (0-4)
Times - Times listed for ticket start, assigned, etc
notified - Used in old ticket system (I plan to get rid of it)
Urgency - Selected by requester, how urgent the ticket is
Location - Location in our warehouse assistance is needed.
FollowUp - currently not in use, will be used to submit follow ups.
isProject - (0-1) is project or not
additionalTechs - Lists additional users on a ticket (Not important for question)
notify - (0-2) at 0, ticket is new and notif should be sent to admins which should set this to 1, when it is 1 it should send a notif to users that are attached to the ticket.
Techs Database:
UniqueID
Username
Password
Name
Level
Disabled
LastTimeSeen
needsNotify (Used in old system, plan to remove)
I'm really stuck here.
You can make it with websockets, or socket.io.
Then the js of multiple clients will connect with that socket will notify all connected people about they ticket
You can change your update statement to something like:
UPDATE tickets SET notify='1' WHERE notify='0' and Assigned = ''//some user id passed

How to check if USERNAME already exists in PHP/MYSQL?

I'm currently configuring my "User Registration" form in PHP.
Trying to create a simple function to check if the username already exists in the database
After doing my research, I have found that there are several ways this can be done.
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFORE the user clicks the "Submit" button;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTER the user clicks the "Submit" button.
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
So, I went with Option B instead.
And, I got it working.
Here is the simply query I used :
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
The only problem is : the registration form itself disappeared.
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
Probably something to do with that "return false" thingy at the end of the query.
But, I am not sure.
(a) How can I get the error message displayed on the form-page itself?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function() ??
Thanks
UPDATE: Here is my form code.
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
I was able to find the following jQuery code :
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
According to Google, the following function is what I need :
Replace $(‘#check_username_availability’).click(function(){ … with $(‘#username’).keyup(function(){ …
(c) Isn't there any way to actually insert that JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission.
Below your input box create a
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
You may use the script as
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
You can disable the submit button and add a span message near the input field.
Check this code:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
put this
include([your validating php file]);
and in your form action link to your login form file.
note : your login file have to be php file.

yii framework where method isn't saving properly

I am using Yii framework and I am creating a register page for the user. In order for a user to create an account, they need to enter in a ticket code. A widow form pops up and they fill out the ticket code, it ajax validates it properly and stores it as a session variable. The popup window closes and allows the user to fill out the rest of the form and submit it. The form should then validate the information, create the user, reasign the ticket's user_ID to the new user_ID, and load the page /ticket/mytickets.
what happens, the ticket is confirmed that it exists, saves it into the session, the user is created, the ticket reassign method gets called, the ticket is never reassigned, and the page reloads. When I echo out the page on the reload, it shows the correct information for the user_ID, and the ticket_ID.
Any hints would help for debugging this would be helpful. Thank you
//controler
public function actionRegister()
{
$model=new User;
$valid = false;
//check to see if valid
if(isset($_POST['User'])){
$valid = $model->checkValid();
}
if($valid)
{
$model->attributes=$_POST['User'];
$user_ID = $model->ID;
if($model->save()){
//save ticket to user
$reassigned = Ticket::model()->reassign_with_IDs($_SESSION['ticket_ID'],$user_ID);
if($reassigned){
unset($_SESSION['ticket_ID']);
//redirect to mytickets
$this->redirect(array('/ticket/mytickets'));
}
}
}
$this->render('register',array(
'model'=>$model,
));
}
//model
public static function reassign_with_IDs($ticket_ID,$user_ID){
$ticket = Ticket::model()->findByPK($ticket_ID);
$ticket->user_ID = $user_ID;
if($ticket->save()){
return true;
}
else{
return false;
}
}
$model->ID is only set after $model is saved. Therefore your code should read:
if($valid)
{
$model->attributes=$_POST['User'];
if($model->save()){
//save ticket to user
$user_ID = $model->ID;
$reassigned = Ticket::model()->reassign_with_IDs($_SESSION['ticket_ID'], $user_ID);
You can however get rid of the reassign_with_IDs function and the unnecessary variable user_ID and just explicitly set the ticket using:
$reassigned = Ticket::model()->updateByPk($_SESSION['ticket_ID'], ['user_ID'=>$model->ID]);

PHP with javascript

I've looked around different questions relating this topic, but none have what I need. I seems simple, but it's still not working. Logically I thought it would work. I have a login form, where I query a select for the user and the password, after that I check if the user and the pw are empty, if not I check if it's in the data base. If it's in the data base redirect somewhere else. Here's the thing, when I load the page, I don't see the txtBox or anything. If I delete the php chunk, everything works fine. Any advice or help would be appreciated.
What I wrote:
<html>
<head>
<link rel = "stylesheet" href = "longInStyle.css">
<script>
function fieldValidation()
{
if( document.getElementById("username").value == "" || document.getElementById("username").value == " " )
{
alert("The username field is empty. Please, enter a username");
document.getElementById('username').focus();
return false;
}
else if(document.getElementById("password").value == "" || document.getElementById("password").value == " " )
{
alert("The password field is empty. Please, enter a password");
document.getElementById('password').focus();
return false;
}
else
{
<?php
include 'config.php';
$usr = $_POST["username"];
$pass = $_POST["password"];
$usrCount = 0;
$passCount = 0;
$SQLUsr = " SELECT USERNAME FROM Users WHERE USERNAME = '$usr' ";
$result = mysql_query($SQLUsr);
$SQLPass = " SELECT PASSWORD FROM Users WHERE PASSWORD = '$pass' ";
$result2 = mysql_query($SQLPass);
$usrCount = mysql_num_rows($result);
$passCount = mysql_num_rows($result2);
if($result == 1)
{
$SQLLvl = " SELECT USERLEVEL FROM Users WHERE USERNAME = '$usr' ";
$result3 = mysql_query($SQLLvl);
if($result2 == 1)
{
if($result3 == "Super")
{
header("location:superUserMain.html");
}
else
{
header("location:editMain.html");
}
mysql_close($db_handle);
}
else
{
<script>
alert("The wrong password.");
document.getElementById('password').focus();
</script>
}
}
else
{
<script>
alert("The wrong username.");
document.getElementById('username').focus();
</script>
}
?>
return true;
}
}
</script>
</head>
<body>
<form method = "post" onsubmit = " return fieldValidation()">
<div>
<div>
Username
</div>
<input type = "text" name = "username" id = "username">
</div>
<div>
<div>
Password
</div>
<input type = "password" name = "password" id = "password">
</div>
<div>
<input type="submit" id = "logIngBtn" name = "logInBtn" value = "Login">
</div>
</form>
</body>
</html>
I saved it as a php file.
config.php has the data base credentials. Username, password and everything else to access it.
To expand on John Condes comment:
You're using JavaScript to control whether PHP code will be executed. This isn't possible (at least not in the way you're trying to do it). PHP code runs on the server, before anything is sent to the client (the users browser). JavaScript (in your context, at least) only runs in the client (the users browser). By the time your JS decides whether the PHP should run, it's too late. The browser has no understanding of the PHP code you're giving it.
I'd suggest starting with a good tutorial on how to build an AJAX login form with PHP and MySQL.
Ignore the haters man...
To help you out though it might be a idea to do what John Conde and mchandleraz said. But to be fair if you are new to this then I think you are doing really well... I still use procedural code as I'm still learning and none of my code is live.
Jay Blanchard is right though mysql_ functions and procedural code is being deprecated and can pose a massive security risk on a live site as someone could potentailly hack your database and steal or your customers information for example. BTW don't take comments on here to heart, programmers tend to be straight talking people by nature.. so don't be surprised if you do something wrong to get slammed for it!
In regards to your question though there are a ton of youtube videos that you can follow on this kind of stuff... failing that buy a book.
Hope you resolve your issue.
Happy coding! :)

Form submit add domain to username field if missing

I have a login form that includes a username and password field.
Users will be able to login using:
Domain\username
And
Username#domain.org.uk
However many users attempt to login using just 'username'
I want to help users by adding domain\ or #domain.org.uk to there username when they enter just 'username', when they click the login button I want to add the domain part of the username.
How can I do this in pure JavaScript?
function insertDomain (){
var txtBox = document.getElementById('Your_Textbox');
if(txtBox.value.indexOf("#") == -1)
{
txtBox.value += "#domain.org.uk";
}
}
On Submit: http://alexking.org/blog/2003/10/01/javascript-onsubmit-handler
Something along the lines of
var username = document.getElementById('username')
if(username.indexOf('#') < 0){
username = usename + '#domain.org.uk';
}

Categories