I am trying to use a form and I want when the user submits this form for mySQL to go into my database and get the account id matching the user that is logged in.I don't have a problem with getting the username but i don't know how I would get the account id from mySQL using the username.
So what I am asking is how would I tell mySQL to go and get the account id matching the username that is logged in and then save the account id in a variable.
assuming this is the structure of the table:
user: id|username|otherInfo
select id from user where username='your submitted username';
extract from the result set and do whatever
Detailed description here, assuming this is the structure of the table:
user: account_id|username|otherInfo
//get your posted value(s) and maybe sanitize a bit
$username=htmlentities($_POST['username']);
/* assuming you set up your db connection, using PDO for this example, i'll
* call that variable $db
*/
//use prepared statement
$pstmt=$db->prepare("select * from user where username=:username");
$pstmt->execute(array(':username'=>$username));
while($row=$pstmt->fetch(PDO::FETCH_ASSOC)){
$id=$row['account_id']; //extracted id
}
Related
I've noticed that the site's user profile edit form allows logged in user to take other user's id and e-mail, which is not good.
To avoid such behavior I've made the query SELECT * FROM users WHERE (username='$username' OR email='$email'); which gets all usernames, all e-mails and then PHP successfully prevents the form execution if such username or e-mail already exists.
But I've noticed that this query also gets currently logged in user's credentials and prevents the user from changing its other data in case username or e-mail are unchanged.
I've decided to exclude the current user by its ID.
I've tried SELECT * FROM users WHERE (username='$username' OR email='$email' OR id!='$id'); to exclude the current user but it still exists and prevents changes in its own profile.
What could be wrong with my query? Any help is greatly appreciated!
I actually have two same tables for users, the second one is for users who still have not activated their profiles. But I suppose there is no reason to search for ID's in that second table as the current user definitely can not wait for activation of its account. Also ID's in those two tables don't match anyway so in case I should exclude a user from the second database I must find a different approach. But I hope I shouldn't.
I do not know you specific case:
SELECT * FROM users WHERE (username='$username' OR email='$email' ) AND id<>'$id'
This query find by email or username and not retrieve by this ID
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.
I'm trying to keep only unique values at username (field inside table professionals, using MySql at the moment).
I got a edit profile page where the user can change his username and other values.
EXAMPLE:
Actual info (not edited):
Name: John;
Tel: 1234567890;
Username: john;
Password:****;
New info (edited):
Name: Jonathan;
Tel: 1234567890;
Username: john;
Password:****;
As you can see the user only changed the name, so I'm inserting all data again in database, but if I verify the username of course it says there is already one at DB.
I need some kind of solution for this, without changing a lot the whole code.
Thanks
What is the need for inserting the whole data once again in the table. Try updating the table.
UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value;
And in your case like
UPDATE table_name SET Name='Jonathan' where Username = 'john'
Really thanks for the answer #Jeff ! I wasn't thinking about the user ID, I can just make a query like this: SELECT * FROM professionals WHERE username = "test" AND id_professional != 3 and after that just verify if there are rows or not.
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).
I am trying to finish this website I am currently creating, but I am kind of stuck.
I want to create a table called "orders" in my DB. I want this table to be related to my users table so that when the user goes to his "orders.php" page (once logged in already) he sees all his current and previous orders.
These would be my table fields/cols:
id
username
ordernumber
description
quantity
total
This is my approach:
Whenever a new order is created, insert all the table fields/cols depending on the user's choice (selected stuff for the order), but the username would be the only value gathered from a $_SESSION or $_COOKIE variable, which holds the username. Then, once the user goes to orders.php, I will execute a query to show all the orders that only that username has ordered. Please note that I do sanitize all my input/output and I do not store sensitive data in my cookies. My system is designed so it only uses the session as the method of authentication, therefore you need to login every time you close the browser but that is fine.
1) Is this a safe approach? Do you have any suggestions/comments?
2) Could you help me construct the query?
I haven't really worked with relational databases, so I am kind of lost. How can I call all the orders from table "orders" where username = "username from the session"?
So far I have this:
"SELECT * FROM orders WHERE username = ? " //(Using PDO)
I know that this will work but my concern is in case of getting a session hijacked or something like that, then a user would be able to retrieve any users' orders, or not?
Thank you for explaining this a little bit further and helping me out!
Cheers!
Be careful! Please don't create a plain text cookie containing a human-readable user id (like user2345995 or OllieJones). It's far too easy for a badguy to fake a cookie like that just by guessing, and then your users' information leaks out.
You're working in php. Therefore you can use php's session mechanism to store your userid and other values. php uses hard-to-guess session ids (SIDs) and stores them in either a cookie or as a sid=1234abcd9875 parameter in URLs.
For the sake of your system's integrity, please read up on this. It's actually a pretty well-designed feature and it's been in the wild for fifteen years or so: it's debugged.
http://php.net/manual/en/session.idpassing.php
If you're using the session system, you basically do this in your first page, your login page.
session_start();
...
$_SESSION['username'] = $username; /* which you get by logging in */
...
On your order lookup page you do something similar to retrieve the username and use it in a query.
session_start();
...
$orderstmt = $pdoconn->prepare("SELECT * FROM orders WHERE username = :username");
$orderstmt->execute( array(':username' => $_SESSION['username']) );
...
while ($row = $orderstmt->fetch()) {
/* use the row's data */
}
$orderstmt->closeCursor();