Use PHP to match username & password with HTML drop down - php

I have a MySQL database called school that is set up like this:
schoolID(1), schoolName(school 1), schoolCounty(Buckinghamshire), schoolUsername(school1admin), schoolPassword(school1password)
I currently have a drop down menu that shows the list of schools and when I type any username and password into the HTML login form I can log in.
I can't seem to work out how I can set it so, depending on the school selection will depend on what username and password to use.
For example, if i select school1 then i can ONLY use school1's username and password.
This is what I have so far for index.php:
<?php
require_once 'databaseConnect.php'; // connects to the databse via this file
if ($conn->connect_error) die ($conn->connect_error); // check the connection to the database. If failed, display error
$sql = "SELECT * FROM school";
$result = $conn->query($sql);
$conn->close();
?>
<html>
<body>
<title>EduKode</title>
<div id="login-form-container">
<p>Log In:</p>
<?php
echo'<div id="schoolSelection">';
echo '<select name="schoolName">';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option>'. $row["schoolName"]. "<br>";
}
} else {
echo "0 results";
}
echo '</select>';
echo'</div>';
//http://stackoverflow.com/questions/10009464/fetching-data-from-mysql-database-to-html-dropdown-list
?>
<form id="login-form" name="contactform" method="post" action="checkSchoolCredentials.php"> <!-- when submitting the form will call the 'authenticate.php' script.-->
<div class="contact-form">
<label>Username:</label>
<input name="username" type="text"> <!-- students created username field-->
<label>Password:</label>
<input name="password" type="password"> <!-- students created password field-->
</div>
<div id="submit-button">
<input type="submit" name="submit" value="Log In">
</div>
</form>
</div>
</body>
</html>
This is for checkSchoolCredentials.php:
<?php
require_once 'databaseConnect.php'; // connects to the databse via this file
if ($conn->connect_error) die ($conn->connect_error); // check the connection to the database. If failed, display error
if(isset($_POST['submit'])) // if submit button is pressed
{
$username = $_POST['username']; //assigns the value of the input box username to $username
$password = $_POST['password']; //assigns the value of the input box password to $password
$query = "SELECT * FROM school WHERE schoolUsername='$username' AND schoolPassword ='$password'"; // Query the database
$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) ==1)
{
session_start(); // start session
$_SESSION['auth']='true';
$_SESSION['username'] = $username; // save session as username
header('location:taskSelection.php'); // if correct, redirect to taskSelection.php
}
else
{
header('location:index.php'); // redirect to index.html if incorrect
}
}
$conn->close();
?>

You were close, what you have to is to send also the schoolname and check if all variable are set:
if (isset($POST['username'],$POST['userpassword'],$POST['schoolName'])
And then just replace :
$query = "SELECT * FROM school WHERE schoolUsername='$username' AND schoolPassword ='$password'"; // Query the database
with :
$query = "SELECT * FROM school WHERE schoolUsername='$username' AND schoolPassword ='$password' AND schoolName='$schoolName'"; //
Now you have to now know that my query is still bad because it's vulnerable to sql injection. You have to use prepare statements instead:
$sql = "SELECT * FROM school WHERE schoolUsername=? AND schoolPassword = ? AND schoolName=?";
if ($query = $conn->prepare($sql)){
$query->bind_param("s", $username,$password,$schoolName);
$stmt->bind_result($result);
while($stmt->fetch()){
// you can work with $result which is an array containing a line of the results
}

Add AND schoolName = "$schoolName" to your SQL statement

Related

log in with session does not work

I have this script sign in first with sql insert into query and redirected to login page. I checked all my queries on phpmyadmin. All queries are working. I do not have any error message in my query. Also it is suppose to show " password/username does not match" message if there is incorrect user/password. After i submit form, the page did not redirect to welcome page and form field clears.
this is my login page
<?php
require_once "./include/variables.inc.php";
$debug =0;
$error_text = "";
$uname = "";
$pwd = "";
session_start();
if (!isset($_SESSION['member_id'])){
if(isset($_POST["submit"])) {
if($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
//die("temp stop point");
}//end ofdebug if
$uname = mysqli_real_escape_string($dbc,trim($_POST['uname']));
$pwd = mysqli_real_escape_string($dbc,trim($_POST['pwd']));
if (!empty($uname) && !empty($pwd)) {
$query = "SELECT * FROM employees WHERE username = '".$uname."'
AND password = '".MD5($pwd)."'";
echo $query;
$result = mysqli_query($dbc,$query) or die ("Error in query". mysql_error());
if(mysqli_num_rows($result)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['member_id'] = $row['member_id'];
$_SESSION['member_name'] = $row['member_name'];
header('Location:index.php');
}
else {
$error_text .= "The username/password are incorrect. Please enter correct username and password.";
}
}
}//end of if(isset($_POST["submit"])
}
require_once('./include/html.head.php');
?>
<body>
<div id="wrapper">
<?php require_once('./include/header.php'); ?>
<div id="side">
<?php require_once('./include/pb.side.php'); ?>
</div>
<div id="content">
<div class="form">
<p class="strong">All Santa helpers log-in here.</p>
<?= $error_text ?>
<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data">
<p>User Name: <input name="uname" type="text" value="<?= $uname ?>"></p>
<p>Password: <input name="pwd" type="password"></p>
<input name="submit" type="submit" value="Login">
</form>
</div>
<div class="rdeer">
<img src="images/login_img.png" alt="Rain Deer">
</div>
</div>
<?php require_once('./include/footer.php'); ?>
</div>
</body>
</html>
and function php is
<?php
function user_authenticated($username, $password) {
if(!empty($username) && !empty($password)) {
$query = "SELECT userName, password FROM employees WHERE userName = '".$username."' and password = '".$password."'";
$result= mysqli_query($dbc, $query)
or die ("Query does not work." . mysql_error());
// If result matched $username and $password, table row must be 1 row
} else {
echo "Query error. ";
}
}
Notice the line mysqli_num_rows($result). Replace it with mysqli_num_rows($result)>0 since that function returns an int.

Querying another table after login

This seems like it should be simple, but I've tried it every which way and can't seem to get it to work.
I have this login script which I adapted from an online tutorial. What I'd like to do is have users sign in with a username and password, and if these are correct, have it go after their lab results in another table (same database) and display them. I can get it to sign in, but that's it. Here's the login code:
<?php //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
/*This is where I'm assuming the new query needs to go.
Query a different table named "data" and pick out information according to
$username which was put in earlier */
echo "<br><a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password   :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div><?php }
?>
</body>
</html>
A "Join" is what I get when I google it but that doesn't seem right. Could someone help?
You can just use a different query for making it easy:
$sql = mysql_query("SELECT * FROM data WHERE user = '" . mysql_real_escape_string($username) . "'");
Then you can process with this.
Please note that you should not use MySQL driver as it is deprecated, use MySQLi(mproved) instead. And you should escape the POSTed values, this is very important!
Your last else statement is trying to echo the HTML.
You should be using mysqli or PDO since mysql is deprecated.
<?php //Start the Session
session_start();
// require('connect.php');
// Establish connection with database
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `people` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
echo "Valid";
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
echo "Username: $username";
echo "Session Username:".$_SESSION['username'];
// This is where I'm assuming the new query needs to go.
// Query a different table named "data" and pick out information according to $username which was put in earlier
echo "
Logout";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="test.php" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div>
</body>
</html>

Differentiate between admin and user php

Im creating a website where users can login to buy books and collect them from store. I have a login screen where both normal users as well as staff use to login. However im trying to find a way to differentiate between normal users and staff.
I have a table called "users" where one of the columns is called "account_type" which can hold a value of U for normal user and A for admin.
this is the code i currently have:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$query = mysqli_query($mysqli, "SELECT * FROM users where Username='$user' AND Password='$pass'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
}elseif ($rows["account_type"] == "A"){
header ("location: adminHome.php");
}else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
Line 24-30 is where ive put the check but it doesnt seem to work.
I dont get any errors it just skips to the validation part when i try the admins login details and says "username or password is invalid" It does login as the normal user however.
Any ideas?
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
}elseif ($rows["account_type"] == "A"){
...
}
Take a closer look at this. You are setting $rows with mysqli_num_rows, it will not be an array and should only be an integer. You need to use a fetch function to get the column data. The fetch would be run using the MySQLi statement variable (in your case the return value of mysqli_query or $query. Read more about fetch here: http://php.net/manual/en/mysqli-stmt.fetch.php
P.S. Your code a little messy. You use stripslashes then real escape, why not use prepared statements? They are safer and more efficient because they let the DBMS (MySQL) handle the variables. Read more about prepared statements here: http://php.net/manual/en/mysqli.prepare.php

How to access specific mySQL data rows and columns after logging in?

This script below is what I'm using to check to see if the user name and password is in my database. This is fine, what I want is now to stay within the row that username and password is found in. In the same row under different columns is more information about the user. I would like to display some of this information in various divs. Not all of it. Examples of the columns other than Password and Email would be "FirstName" and "LastName"
There is also an "Id" column it would be great to be able to do something like "you are logged in, you are Id 10101 and then display FirstName and LastName from current Id.
<?
session_start();
//then do rest of the stuffs//
?>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Email: <input type="text" name="Email" /><br />
Password: <input type="password" name="Password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$sql = "SELECT * from stores_db WHERE Email = '{$Email}' AND Password = '{$Password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1)
{
echo "<p>Invalid Email or Password combination</p>";
}
else
{
$recordset = mysqli_fetch_array($result);
$temp_firstname=$recordset['FirstName'];
$temp_lasttname=$recordset['LastName'];
$temp_id=$recordset['Id'];
$_SESSION['user_id']=$temp_id;
header("location:homepage.php"); // direct to your page to show
}
}
?>
Code on homepage.php
<?php
session_start(); echo $_SESSION['user_id']; //to display the id of the logged in user
?>
$sql = "SELECT * from stores_db WHERE Email LIKE '{$Email}' AND Password LIKE '{$Password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1)
{
echo "<p>Invalid username/password combination</p>";
}
else
{
echo "<p>Logged in successfully</p>";
$recordset = mysqli_fetch_array($result);
$temp_firstname=$recordset['FirstName'];
// storing firstname on a variable
$temp_lasttname=$recordset['LastName'];
$temp_id=$recordset['id'];
$_SESSION['user_id']=$temp_id;
header("location:homepage.php"); // direct to your page to show
}
After Doing this,
write
session_start();
echo $_SESSION['user_id']; //to diplay the id of the logged in user
in the page to be foolowed
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
<?
session_start();//at the top most
//then do rest of the stuffs//
?>
<?
session_start();
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Email: <input type="text" name="Email" /><br />
Password: <input type="password" name="Password" /><br />
<input type="submit" name="submit" value="Login" onclick="" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error} </p>";
exit();
}
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$sql = "SELECT * from stores_db WHERE Email = '{$Email}' AND Password = '{$Password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1)
{
echo "<p>Invalid Email or Password combination</p>";
}
else
{
$recordset = mysqli_fetch_array($result);
$temp_firstname=$recordset['FirstName'];
$temp_lasttname=$recordset['LastName'];
$temp_id=$recordset['Id'];
$_SESSION['user_id']=$temp_id;
$_SESSION['lastname']=$temp_lasttname;
$_SESSION['firstname']=$temp_firstname;
header("location:homepage.php"); // direct to your page to show
}
}
?>
Code on homepage.php
<?php
session_start(); echo $_SESSION['user_id']; //to display the id of the logged in user
?>

PHP Login Form - Not Seeing mySQL Rows

Simple Question: Trying to create a php login form. My database is connected successfully. I currently have 1 table row in mySQL. So why is my $numrow variable echoing 0/ Why is my username in my database not being recognized? What am I missing? Please, help. Not a php expert.
Thanks!
<?php
include 'includes/top.php';
?>
<?php
error_reporting(0);
session_start();
$connect = mysql_connect("localhost", "hostname", "password") or die ("Couldn't connect!");
mysql_select_db("djones33") or die ("Couldn't find db!");
$query = mysql_query("SELECT * FROM tm_user WHERE username='$username'");
$numrows = mysql_num_rows($query);
echo $numrows;
if ($numrows!=0) {
while ($row = mysql_fetch_assoc($query)) {
$db_username = $row['username'];
$db_password = $row['password'];
}}
if (isset($_POST["username"])) {
$username = $_POST["username"];
//they did, so now, has the username AND password been entered?
if ((isset($_POST["username"])) && (isset($_POST["password"]))){
//they have, now, is the username correct?
if ($_POST["username"]!=$db_username && $_POST["username"]!=""){
$uerror="<p class='error'>* The username you entered is not correct.</p>";
//echo "$uerror";
} else {
echo "";
}
//now, is the password correct?
if ($_POST["password"]!=$db_password && $_POST["password"]!=""){
$perror="<p class='error'>* The password you entered is not correct.";
//echo "$perror";
} else {
echo "";
}
//they haven't entered a username, so...
if ($_POST["username"]=="") {
$emptyu="<p class='error'>* You must enter a username.</p>";
//echo $emptyu;
}
//they haven't entered a username, so...
if ($_POST["password"]=="") {
$emptyp="<p class='error'>* You must enter a password.</p>";
//echo $emptyu;
}
//if the username and password are correct, give them the welcome page!
if ($_POST["username"]==$db_username && $_POST["password"]==$db_password) {
echo "";
$_SESSION['username']=$db_username;
//$welcome = "Welcome, ".$user. "! You have successfully logged in.";
}
}
}
?>
<h2><span class="green_title">Welcome</span><br><span class="title_size">to YOUR.to-do!</span></h2>
<section id="login_area">
<div id="login_title">
<p>Login</p>
</div>
<div id="form_area">
<form action="login.php" method="post">
<?php echo $uerror; echo $emptyu;?>
<input type="text" name="username" placeholder="username" id="username"/><br/>
<?php echo $perror; echo $emptyp;?>
<input type="password" name="password" placeholder="password" id="password"/><br/>
<input type="submit" name="submit" value="LOGIN" class="button"/>
</form>
</div>
</section>
<footer>
<p>New user? | Register</p>
</footer>
</div>
</div>
</body>
</html>
Have a look at PHP's built-in Password Hashing Functions and the PDOStatement Class. When your users register be sure to use password_hash() on the passwords they submit before saving them in your database. And when you query your database use PDOStatements and bound parameters to keep your site safe from SQL injection attacks.
Your log in script should look something like this:
$db = new PDO('mysql:host=localhost;dbname=Database_Name', 'Username', 'Password');
$ps = $db->prepare("SELECT * FROM tm_user WHERE username = (:username)");
$ps->bindParam(":username", $_POST["username"]);
$ps->execute();
$result = $ps->fetch(); // $result is an array representing the row in tm_user with the submitted username
if(count($result) === 0)
{
// username not found
}
else if(password_verify($_POST["password"], $result["password"]) === false)
{
// password is incorrect
}
else if(password_verify($_POST["password"], $result["password"]) === true)
{
// give them the welcome page!
}
Remember: password_verify() will only work if you used password_hash() on the password before storing it in the database.

Categories