If I have a query,
SELECT (...) FROM User WHERE Username = (...) AND Password = (...);
and the user types in an invalid Username is there a way to pick up that it was specifically the Username that was incorrect?
This is so that I can give more specific error messages to the user, like "User does not exist" etc...
SELECT COUNT(*) AS `count` FROM `User` WHERE `Username` = ...;
if( $result['count'] < 1 )
{
// no user
}
// repeat for pass.
I would select the username and then a bit-field on if the password matched. So remove the password part from the WHERE clause, and move it into the SELECT clause. Then, no matching rows means invalid username, and if you have a row, you need to check that field to see if the password matches.
SELECT (...) IF(password=?, 1, 0) as success
FROM User
WHERE Username = ?
If you're adamant about doing it this way, you can do:
SELECT password FROM user WHERE username = ?
If there's no record found, the username doesn't exist. If it does, you can now compare the password.
Related
> i ve got 4 separate tables to store login data.
>>> tables are **admin_login staff_login >tutor_login student_login**.
>>>>>> my php registration form is storing data into this fields.
now i need some suggestion how i can make login script?.
I've got the login form ready.
For starters why have 4 tables? Why not have 1 with a login type field??
The general rules are the same for multiple tables as for one. You want to check for the username / email address, then check the passwords.
Start off querying your tables for the username email address. Count the results. If their is a result then check the password (with whatever if any encryption you're using) matches and log them in. If there are no results throw a message to the user saying there is no one matching that username / email, if the password doesn't match up then tell them that.
I'm not going to write it for you but here's the gist of it:
$query = mysql_query("CHECK FOR EMAIL ADDRESSES OR USERNAMES"); // Just query multiple tables if you're going to do it this way (I'd still use the one though)
$count = mysql_num_rows($query);
if ($count > 0) { // Email address exists
// Check the passwords match up
if (PASSWORDS MATCH) {
// Do your login here
} else {
// Password wrong error
}
} else {
// No username error here
}
You could work out something using UNION's but it would be better to re-factor the database to a single table with a field denoting if they are Admin/Tutor etc.
either you can use a join query first or you can have one unified table for all users with an accessLevel field like:
users-table:
username | passwordHash | accessLevel
---------+--------------+------------
abc | mnbdjhgs | admin
pqr | kfgjkfbb | stud
then you can simply check userdetails you get from the loin form like:
$result = $mysqli->query("SELECT passwordHash, accesslevel FROM users WHERE username = '{$username}' ");
if($result)
{ $data = $result->fetch_assoc();
if($data)
{ if($password === $data['passwordHash'])
{ //identify the user-type here..
$accesslevel = $data['accessLevel'];
//now u can do session initialization and other stuff..
}
}
}
else
{ //show wrong username or password messages
}
how to join 3 tables with one common field like
table1:c_id,username,password,c_role
table2:p_id,username,password,c_role
table3:s_id,username,password,c_role
in this c_role field is common
here i assigned
enum '1' for c_role in table1
enum '2' for c_role in table2
enum '3' for c_role in table3
for giving rights to 3 different users like corres, principal and for a staff when they login..
Now when they login it should identify the user and take them to their page..
You should have one table that contains the following columns:
id (unique, primary), username, password, role (INT, would be assigned 1-3 for principal, staff or corre depending on the user)
Additionally
You could have another table called roles if you want set up like this:
id (unique, primary), title (options for title would be principal, staff, or corres)
When the user logs in just do something like
if($role == 1){
// redirect to principal page
}
elseif($role == 2){
// redirect to staff page
}
elseif($role == 3){
// redirect to corres page
}
I'm not certain but I believe this would work as well. Try this query.
(SELECT '1' AS role FROM table1 WHERE username = $username AND password = $password)
UNION ALL
(SELECT '2' AS role FROM table2 WHERE username = $username AND password = $password)
UNION ALL
(SELECT '3' AS role FROM table3 WHERE username = $username AND password = $password)
Assuming the user is only located in ONE of those three tables then it should match the username and password and find out which table the user is coming from. Then you can pull out the role by using
$role = $row['role'];
If the username/password combination is incorrect then $role would be empty or you could fetch the number of rows [using $iscorrectuser = mysql_num_rows($query)] where there is a match and the number of rows would be 0. You could then redirect the user trying to log in with a "Unsuccessful login" error message.
The only joins would be on username (and password ?) unless c_id, p_id and s_id are all the same id?
You can't join on role seeing as they are different in each table, aside from an utterly daft role = 1 in Table1 is the equivalent of role = 2 in table2.
Do you mean a union? As in you want
User Password Role
Fred Fr3d 1
Fred ??? 2
Fred ??? 3
Not sure what you are trying to achieve with this schema, but it breaks near every rule in the book, and doesn't seem to meet your needs....
Based on your comment, one way you might look at is.
Is
Users (UserID, UserName, Password etc) Key UserID
Roles (RoleID, RoleName etc) Key RoleID
UserRoles(UserID,RoleID) Key UserID,RoleID
You need to learn a bit about databases particularly normalisation, first three forms should do for most things.
Then
Select UserName, Password,RoleName From Users
inner join UserRoles on Users.UserID = UserRoles.UserID
inner join Roles on UserRoles.RoleID = Roles.RoleId
and such like become possible and efficient.
session and include functions are given:
session_start();
include("config.php");
if(isset($_POST['T_UserName']) && isset($_POST['T_Password']) && !empty($_POST['T_UserName']) && !empty($_POST['T_Password']))
{
username and password sent from form:
$T_UserName=$_POST['T_UserName'];
$T_Password=$_POST['T_Password'];
To protect MySQL injection:
$T_UserName = stripslashes($T_UserName);
$T_Password = stripslashes($T_Password);
$T_UserName= mysql_real_escape_string($T_UserName);
$T_Password = mysql_real_escape_string($T_Password);
$sql="SELECT * FROM login WHERE username='$T_UserName' and password='$T_Password'"; $result=mysql_query($sql);
Mysql_num_row is counting table row:
$count=mysql_num_rows($result);
If result matched $T_UserName and $T_Password, table row must be 1 row :
if($count==1)
{
Register $T_UserName, $T_Password and redirect to file "correspindex.php" :
session_register("T_UserName");
session_register("T_Password");
redirect to error page or display error message then :
if(isset($_POST['emp_role'])
{
$userinfo = mysql_fetch_assoc($sql);
$emp_role = $userinfo['emp_role'];
if($emp_role == 1)
{
header("location:corrrespondindex.php");
}
elseif($emp_role == 2 )
{
header("location:principalindex.php");
}
elseif($emp_role == 3)
{
header("location:staffindex.php");
}
closes out if the user DOES exist:
header("location:loginhome.php");
}
else
{
echo "Wrong Username or Password";
}
}
}
php is closed
this is the php code im getting so many error
i create 1table with id,username,password and role(ENUM,values as'1','2','3' –
any else shud i do in the code???
I have the following function:
function login_check($email, $password)
{
$email = mysql_real_escape_string($email);
$password = md5($password);
$login_query = mysql_query("SELECT COUNT(`id`) as `count`, `id` FROM `table_name` WHERE `email`='$email' AND `password`='$password'");
return (mysql_result($login_query, 0) == 1) ? mysql_result($login_query, 0, 'id') : mysql_error();
}
I want it to check if the user login is correct in two different tables not only one since I've made another table for users who have authenticated their twitter account with my site.
You'd be better off with a single table that has an "authenticated with Twitter" flag but you can check both with something like this:
select exists(
select 1 from table_name where email = '$email' and password = '$password'
union
select 1 from twitter_table where email = '$email' and password = '$password'
)
MySQL will give you a one (AKA true) if at least one of the tables has what you're looking for and a zero (AKA false) if neither has a match.
Using the select exists(select 1...) trick will also be faster than counting as the database only needs to find one match or check the indexes to know that there are no matches before it returns from the query.
You could create an union view of both tables:
CREATE VIEW combined_accounts AS
(SELECT id, twitter_mail AS mail, password FROM twitter_accounts)
UNION
(SELECT id, mail, password FROM my_accounts);
How do I check if a username exists using PDO? All I need to know is a bool true (exists) or false (does not). I have the initial parts set up but am unsure what to do next
$sthandler = $dbhandler->prepare('SELECT username FROM userdb WHERE username=? LIMIT 1');
$sthandler->execute(array('username'));
// ... What's next?
Check for the row count:
if ( $sthandler->rowCount() > 0 ) {
// do something here
}
Just grab the row:
if( $row = $sthandler->fetch() ){
// User exists: read its details here
}else{
// User does not exist
}
$username_exists = (bool) $sthandler->fetchColumn();
Note that you can even optimize the query a tiny bit since actually you don't need to select the username.
SELECT username FROM userdb ...
becomes
SELECT 1 FROM userdb ...
Hello I have a table with 11 in and about 7 tables with 1 in
Each has 2 column username and clicks. The problem is that i have to add up all the clicks were username = username Is there anyway i can do that ?
I'm using
$result1233 = mysql_query("SELECT * FROM urls_non_loggedin WHERE username='$_SESSION[username]'");
$num_row3s = mysql_num_rows($result1233);
But I want to add up all the clicks "the column name " where username = $_SESSION[username]
If you get what I mean ?
So there is a table with 2 columns clicks and username I want to grab all the numbers in clicks and add them up were username = usersname
You can use the SQL SUM operator. Like this:
SELECT username, SUM(clicks) As number_of_clicks FROM urls_non_loggedin WHERE username='$_SESSION[username]' GROUP BY username
Although you should be careful from passing variables into your queries that you have not sanitized.
EDIT: I replaced * with username in accordance to the comment from the moderator