Going from database to sessions - php

Well I have my register done all nice, as required fields it holds your email, name, and password. When you log in it asks for your email and password.
When they log in I have it so that they have their email stored in a session, but how do I get their firstname stored in a session, even though they didn't type it? Thanks.
The thing is, I don't know the users first name so...

When the user logins in with their username/password and after verification of the information, query the database for their record. Set the returned value(s) into the session. If you are already getting information about the account, add a table join (if in separate tables) or the columns.

When they log in and you are checking the login credentials (email and password), if you find the user, select their first name as well and store it in another session variable:
$query = 'SELECT firstname FROM users WHERE email = $email AND password = $password LIMIT 1';
...
if ($result && mysql_num_rows($result) == 1) {
$row = mysql_fetch_object($result);
$_SESSION['firstname'] = $row->firstname;
...
That might not be exact based on table and column names, but that's the general idea.

Related

On succesfull log in should I save user data In Sessions, global variables or query on every page?

If I have an authentication system with user name and password, that queries data from the data base on log in, like user name, user id, profile description, etc. How should I save this data so I can show it on every page, for example if I want to show the user name on the navigation bar on every page as long as the user is logged in.
Should I save the user id in a session and use it to query the user data on every page in order to show the user data on that page ?
login.php
Query the users table to get the user id based on user name and password
SELECT uId FROM user WHERE pass = $_POST['pass'] and name = $_POST['name'];
$_SESSION['userId'] = $res['uid'];
otherPages.php
SELECT user_name FROM users WHERE uid = $_SESSION['userId'];
Should I query this info only once when the log in happened and save everything in sessions ?
login.php
Query the users table to get the user id based on user name and password
SELECT * FROM user WHERE pass = $_POST['pass'] and name = $_POST['name'];
$_SESSION['userId'] = $res['uid'];
$_SESSION['name'] = $res['user_name'];
$_SESSION['description'] = $res['des'];
otherPages.php
echo $_SESSION['name'];
What is the best way to keep user data between pages after log in ? querying on every page works well until now but it feels redundant. How is this usually handled ? Thank you.
all queries in this question are purely for example, the code that I actually use is well formatted :) (probably).
Passwords are also hashed using php password_hash();
This purely depends on your needs. If you know that the user data can be changed externally e.g. by another user, event,.. then you should fetch the data from database every time to keep them updated. However if the only one who can modify the data is user itself, then you can safely keep this info in session and it MIGHT help your application. It doesn't really matter which one you choose as the time difference will be minor.
EDIT:
Also, you should identify user by his username only.

Validate if username exist when editing info PHP and SQL

I have a question and I can't find a correct way to solve my problem.
I have a application where the username is the emailadres. A user can change his/her information on a page called edit.php
I have also a validation in place that is checking if the username exists when editing. This to prevent that user A can edit his username in a username of another existing user. I do this with the following function.
$sql=mysql_query("SELECT username FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'");
if(mysql_num_rows($sql)>=1) { echo "Exists"; } else { /* update database */ }
This works, only now I have a problem. Because the user can edit in the editform not only the USERNAME, but also PHONE, ZIP, CITY. If a user edits his ZIP, CITY or PHONE I will get logically 'exists', because the username is also posted in my editform.
My question: How can I set it up so that the username only is checked when it is different from the current username of the user. For example, if test#test.com (username) edits his information and it remains test#test.com it won't be checked and when the username test#test.com is edited in test123#test.com it will be checked?
I think I need to set up a double check like if mysql_num_rows($sql)>=1 OR ==
Am I right? any help would be great.
For the new username to be valid, your check should be: there is no row with this username, or the row is actually the current user.
So you need to select the ID in your query (instead of the username, which you don't need) and change your if statement to test "no result, or one result with ID = current user ID".
Of course I'm assuming you have an ID as a primary key of your table, and that this ID is stored in the session for the current user.
Also, consider using PDO instead of mysql_query...
This can be resolved by doing a verify user with ajax before processing the form, using the SQL query you are currently using:
SELECT username FROM users WHERE username='$user'
If ajax query return "true" or "not empty data", user exist and not is usable, else, user is available for use.
A few months ago I did something similar in a Signup form. On "username" field, if the user is available turns green, if not available, it turns red. The verification is done by changing field.
Signup Example with verification
Recommend to use PDO instead of php mysql_query (is deprecated in new PHP versions).

PHP & MySQL - Checking if database entry does NOT exist?

I'm collecting the birthdates of users in my system, doing so by linking the the user's unique ID to their birthday entry in another table.
To prevent users from accidentally/purposefully entering two birthdate entries for their accounts, I'd like to remove to the entry form for birthdays IF the user has already entered a birthday prior.
For instance:
$value = mysqli_query("SELECT bd_user_id FROM user_birthdate WHERE
bd_user_id="$user_id";");
From that data, how will I be able to return some form value to determine if whether the user's ID has already been index in user_birthdate or not? (Where $user_id = The current user's ID)
Or perhaps I'm taking the wrong approach here? The logic behind it is what's been getting me.
How can I check if whether a value is NOT indexed in a database table?
You normally query the database as you did
$value = mysqli_query("SELECT bd_user_id FROM user_birthdate WHERE bd_user_id="$user_id";");
Than you use mysqli_num_rows(), and check if it returns 0.
$num_rows = mysqli_num_rows($value);
if($num_rows > 0){
//exists
}else{
//doesn't exist
}
**Sorry, as Devon said in your case it's mysqli_num_rows not mysql_num_rows.

Login php if else condition for 2 database table

Hi everyone i think this is good question for everone.
I am try to make a login page. But i have one problem. I have 2 users table in my database . First users table is for normal user and second users table is for vip user.
Under the code using for normal user. i want to make if email and password is for vip user then open vip_user_profile.php if not email and password is vip user then check the normal users table if there is a email and password then open normal_user_profile.php how can i do this. Is anyone can help me ?
What i can add a code in my login php code ?
My code is this.
<?php
include("includes/connect.php");
if(isset($_POST['login'])){
$email = $_POST['email'];
$password = $_POST['pass'];
$check_user = "SELECT * FROM users WHERE password='$password' AND email='$email'";
$run = mysql_query($check_user);
if(mysql_num_rows($run)>0) {
echo"<script>window.open('normal_user_profile.php','_self')</script>";
}
else {
echo"<script>alert('email or password is incorrect!')";
}
}
?>
If you insist on storing information in two tables, you can still get the data using one query. There are many ways to do that, but here's one that you might find interesting:
select
sum(usertype) as usercheck
from
( select nu.username, nu.password, 1 as usertype
from NormalUser nu
union all
select vu.username, vu.password, 2
from VipUser vu
) u
where
u.username = '$username' and
u.password = '$password'
This query will return a single integer field, which can have either of these values:
null: No combination exists for username/password
1: User is a normal user
2: User is a VIP user
3: Both tables contain a user with the same password.
Note that in cases of 1 and 2, it is still possible that the same username exists, but with a different password.
Now, to solve that, you can put all users in one table and give them a user type. You can make a lot of extra columns that you can leave empty. If you really want to store that information in a separate table (and there are good arguments for that), you can still create one table with basic user information, such as uername and password. Then, in the VipUsers table, you don't store username and password, but only store the id of the user and the additional information. This user id should be the primary key of both the Users table as the VipUsers table. Also, it should be a foreign key in VipUsers, referencing Users, so that you can not have an orphan VipUser record, without basic user information.
However, I would opt for a single table with a type and nullable fields. And I've got the feeling that that matches better with your current skill level as well.
Hi i think this tinking help you. I've read all your questions. You have two types of users. However, users have a different situation in. It truth businessname. You need to concentrate on it. *If the user uses this name when logging in to your website then his profil automatically open vip_user_profile.php Of course you'll have to do it on your code.*
this is easy to use for you. For your vip user header("vip_user_profile.php"); or header("normal_user_profile.php");

Show mysql data where username is the same

I have a mysql table which has data from all flight bookings on my booking system. When a user books a flight, the details of that booking are stored in that table along with their username.
Now, I'm making a page where all of the user's previous flights are shown in a HTML table, and everything works except the code which filters results to those only from that user.
This is the (part of) code I'm using;
$query_string = "SELECT name, seats, departure, destination, class, username, miles, timestamp FROM $tablename WHERE username IN ('$username')";
The username field is where the user who booked the flight's username is stored, and the $username variable contains the current logged in user's username. What I'm trying to do is only show the fields where $username matches username (hence only showing bookings for the current user).
When I use the above code without WHERE username IN ('$username'), it displays all the data, but when I add the above code, it displays nothing when there are matches.
If anyone could help fix my code I would greatly appreciate it.
Thanks!
You're using IN incorrectly. IN compares comma-separated lists of strings or values. This can be literal:
WHERE username IN ('user1', 'user2', 'user3')
OR it can come from a subquery:
WHERE username IN (SELECT username FROM users)
If you want an exact match, your WHERE clause should be
WHERE username = '$username'
If that still doesn't work, you MUST verify that you're sending your database the correct query.
echo $query_string;

Categories