Checking if users exists - php

I did a lot of googling and tried many methods but checking for username existence in Mysqli database is not working. Everything is correct but still the user is getting registered even if there is a username in Database. Please help...My php version is 7 and phpmyadmin is 5.6. My code :-
<?php
session_start();
if (isset($_SESSION['id'])) {
header('Location: user.php');
die();
}
else {
if($_POST['submit']){
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$passhash = hash('sha512', $password);
$passhash2 = hash('sha512', $passhash);
$strlen = strlen("$password");
if ($strlen < 10) { {
$lesspass = "Use password of atleast 10 letters";
}
}
else {
$date = date("Y-m-d");
require ('setup.php');
$conn = new mysqli($localhost, $hostuser, $hostpass, $hostdb) or die("conn died");
$query1 = "SELECT * FROM member WHERE username = '$username'";
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($query1) > 0) {
die ("Username in use");
}
else {
$query2 = "SELECT from member WHERE email = $email";
$result2 = mysqli_query($conn, $query2);
if (($result2) > 0) {
$ee = "Email already exists";
}
else {
$query = "INSERT INTO member(username, password, registered, email, activated, status) VALUES('$username', '$passhash2', '$date', '$email', '1', '0')";
$result = mysqli_query($conn, $query);
if($result) {
header('Location: login.php');
}
else {
echo "There was a problem while connecting";
}
}
}
}
}
}
?>

I think the error is that you use mysqli_num_rows on the query string. Do it on the result:
if (mysqli_num_rows($result1) > 0) {
Also, you should take care about SQL injections (escape or use prepared statements), but that's another story. Not sure if strip_tags is sufficient.

Related

Error handling checking database with else if for existing email

Im stuck with some code. Im pretty new to this.
If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if (empty($username)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($email)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
$sql = "SELECT username FROM user WHERE username='$username'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0) {
header("Location: ../signup.php?error=username");
exit();
} elseif ($uidcheck < 0) {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
header("Location: ../signup.php?error=email");
exit();
} else {
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
}
When the emailadress already exists in the database it should exit and add a parameter to the header.
Thanks in advance!
Sven
Your code may does the purpose. But that is not good enough to read/debug.
if( !isset($_POST["username"]) || !isset($_POST["email"]) || !isset($_POST["pwd"]) || empty($_POST["username"]) || empty($_POST["email"]) || empty($_POST["pwd"]) )
{
header("Location: ../signup.php?error=empty");
exit();
}
$sql = "SELECT username FROM user WHERE username='".mysqli_real_escape_string($username)."'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0)
{
header("Location: ../signup.php?error=username");
exit();
}
else
{
$sql = "SELECT email FROM user WHERE email='".mysqli_real_escape_string($email)."'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
header("Location: ../signup.php?error=email");
exit();
}
else {
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
Here are my Recommendations:
Always check if an variable is declared in the scope using isset() function. If the value of "username" or "email or "pwd" is not submitted in the POST request, your code will throw a Fatal Exception and rendering stops there.....
Don't put the value submitted by the User directly into the SQL query....This will make your web application Vulnerable to SQL Injection Attack.
Try this..
You are checking the MySQL resulted value in a wrong manner. For Example Email is already existed in you DB then your Query results Value, then you don not check with < or > just try with either it is empty or not.
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if (empty($username)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($email)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
echo "Username check";
$sql = "SELECT username FROM user WHERE username='$username'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if (!empty($uidcheck)) {
header("Location: ../signup.php?error=username");
exit();
} elseif (empty($uidcheck)) {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
echo $emailcheck = mysqli_num_rows($result);
if (!empty($emailcheck)) {
header("Location: ../signup.php?error=email");
exit();
} else {
echo "asdasd";
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
}

password_verify stops working after changing hash

I'm working on implementing the ability for users to edit their passwords.
I'm using PASSWORD_BYCRYPT, and password_verify works fine after creating a user, but as soon as a user edits their password, it stops working.
Password change:
else if (isset($_POST["submitUpdateSettingsPW"])) {
$passwordText = $_POST["passwordChangeInput"];
$userID = $_SESSION["userID"];
$passwordNew = password_hash($passwordText, PASSWORD_BCRYPT);
$sql = "UPDATE users SET password = '$passwordNew' WHERE id = '$userID';";
if (mysqli_query($conn, $sql)) {
header("location: settings.php");
}
else {
header("location: settings.php?message=Something+went+wrong.+You+may+not+have+the+permissions+to+do+this.");
}
}
Password creation
else if (isset($_POST["submitSignup"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$password = password_hash($passwordText, PASSWORD_BCRYPT);
$signupSQLCheck = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $signupSQLCheck);
if (mysqli_num_rows($result) == 0) {
$signupSQL = "INSERT INTO users set email = '$email', password = '$password'";
mysqli_query($conn, $signupSQL);
header("location: login.php?message=Your+account+is+active.+You+may+now+login.");
}
else {
header("location: login.php?message=This+email+is+already+registered.+Do+you+want+to+<a href = 'login.php'>login</a>?");
}
}
Password verify (works fine until changing password)
if (isset($_POST["submitLogin"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$loginSQL = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$result = mysqli_query($conn, $loginSQL);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
$hash = $row["password"];
if (password_verify($passwordText, $hash)) {
$_SESSION["user"] = 1;
$_SESSION["userID"] = $row["id"];
header("location: index.php");
}
}
else {
header("location: login.php?message=Incorrect+email+or+password.+Do+you+want+to+<a href = 'signup.php'>sign up</a>?");
}
}
Thanks in advance

If else statement error confused

Hello guys I was confused using the if else statement I know it is the basic in conditioning also other languages. Don't know what to do here, I would like that it has an if condition(check) then also inside I want that it has an else if but my problem is I have to else statement which is wrong cause I know that else statement will be use at the end of a condition
Here's my code:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
}
Please help me
You have imbricated your blocks, try this:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
With an indentation, this kind of problem is easily visible.
This can be ok:
if ( //validate the email
filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match('/#.+\./', $email)
) {
$result = mysql_query (
"INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())"
);
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}
}
Try this one :
if (filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/#.+\./', $email)) {
$result = mysql_query ("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}

Can't fetch data from MySQL (php) (Re-edited)

I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.

Insert data (only 1 time) in while loop using PHP

I have the PHP code as below:
<?php
if(isset($_POST["tbn_submit"])){
$userName = $_POST["text_username"];
$pass = $_POST["text_password"];
//$sql = "SELECT * FROM tbluser WHERE username='".$userName."' AND password='".$pass."'";
$sql = "SELECT * FROM tbluser";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0){
while($row= mysql_fetch_array($res)){
$username=$row['username'];
$userpas = $row['password'];
$user_id=$row['userId'];
$user_role=$row['possition'];
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if($userName == $username && $pass == $userpas){
if($user_role=="Admin"){
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}else{
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else if($userName == $username && $pass != $userpas){
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
else if($userName != $username && $pass != $userpas){
//In this point I got insert multi time so I want it insert only 1 time to database
$query = "INSERT INTO tbluser(userId,username,password,possition,user_status) VALUES('','".$userName."','".$pass."','',1)";
$result = mysql_query($query) or die(mysql_error());
$id = mysql_insert_id();
if($result){
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
}
}else {
echo "re";
}
}
?>
This is my login page submission. When the user inputs their username and password, if the username and password are already in the database it will go to test some case like in code, but if the username is in the database but the password does not match it should display wrong password..
If the username and password don't exist in the database, the program should create username and password and go to other page. I have an error with this last case - I have inserted a lot of records in the database with the same data. I know it's because I wrote these entries in a while loop in my code but I don't know any other way of doing this. How can I populate my database with individual records and not write duplicate entries in my while loop?
All your logic is wrong:
there's no need to retrieve ALL the users to check if the user exists,
tbluser should restrict username to be UNIQUE to avoid duplicated entries,
passwords should be hashed,
the INSERT query uses unescaped variables,
inserting non matching user names will lead to have typos stored at the db,
mysql_* family of functions are deprecated
Using PDO
Login user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
$username = $res['username'];
$password = $res['password'];
$user_id = $res['userId'];
$user_role = $res['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
Register user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$check = $_POST["passcheck"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$statement = $dbh->prepare("INSERT INTO tbluser (userId, username, password, position, user_status) VALUES ('', :user, :pass, '' , 1)");
$statement->bindParam(':user',$user);
$statement->bindParam(':pass',$pass);
$statement->execute();
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
Using mysql_query (deprecated)
To validate any user:
<?php
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* This line had the right idea!
*/
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
$username = $row['username'];
$password = $row['password'];
$user_id = $row['userId'];
$user_role = $row['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
To register some user:
<?php
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* Ask the user to type its password twice
*/
$check = $_POST["passcheck"];
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
if (mysql_num_rows($res) > 0) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$query = "INSERT INTO tbluser (userId, username, password, possition, user_status) VALUES ('','".mysql_real_escape_string($user)."','".mysql_real_escape_string($pass)."','',1)";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}

Categories