I'm trying to create a MySQL database that will hold all of my users and logins.
The table columns are:
User_id
passkey
points
The user_id of each user has to be unique, and same with their passkey. Points is just an integer value that I will edit from time to time. Now, when I get a user to my site, I have to check if he is a new user or an old one. I check by seeing if their user_id is in the database already, and if not, I create a new entry to the table that inputs their user_id, passkey, and 0 for points. So, when I create the table, do I still have to specify unique for the user_id and passkey, even though I'll be checking first before creating new entries?
And how would I check if the user_id is already in the system? I'm thinking something like:
SELECT * FROM customers
WHERE user_id='test'
And then count the rows, and if it is zero, I create a new entry, right? I'm trying to make sure I get everything right before I run my code. Thanks.
It's a good idea to anyway mark the fields as UNIQUE, because in the case you miss something in your code, the DB will still catch the error before things break down. I'm not sure why you want the passkey to be unique though, is there anything wrong with two users having the same passkey?
Your query is fine, but I guess you don't really need the actual user details when checking, so you can just ask for the count:
SELECT COUNT(*) FROM customers WHERE user_id='test'
and if the returned value is > 0, the user_id already exists.
You should specify unique and auto increment so that you just fill in NULL and it does it for you.
However, I would worry that you should have usernames and passkeys...
First set the passkey field default to 0. Then for the user_id make it auto_increment. This will go up by one each time a new row is added (e.g. new user). You will not need to check if the user_id is in the system when you insert to the database.
When inserting you just need to specify the passkey, presumably this is the user's password. All of the field editing can be done in phpMyAdmin, under Structure for your tabel.
Related
I'm trying to build a very simple login system for my site (just for practice for a project i'm working on). The way I've decided to implement it is use a table with fields for ID, Name, Password, and username and search for the entered information in the existing table.
For registration, it simply injects the information supplied into the table, and I would like to assign a customer ID number. My idea for assigning an ID number is to simply find the size of the ID column (which will contain the ID's 1,2,3..etc up to the end) and assign the new registration to the length +1. For this purpose i'll need a way to get the size of the column, but I'm just learning php and sql so i'm not sure what the syntax would be.
TLDR; is there a funtion in sql that I can use in php to get the length of a particular column? (i.e the number of entries stored in that column?)
Set the ID column to Primary and Auto increment.
you don't include that in your query it is created on its own.
You'd probably be better off just using an IDENTITY or AUTO_INCREMENT column. The problem with checking for the "size of the column" (by which I assume you mean the count of rows in that column) is that you could end up inserting duplicate IDs, for example:
ID | ...
---------
1
2
4
So if you did a SELECT COUNT(ID)+1 FROM MyTable, it would return 4, and you have an ID collision.
You could do something like SELECT MAX(ID)+1 FROM MyTable, but even then there could be concurrency problems (process A and process B both try to run that query at the same time, before either has a chance to insert the new ID of 5). You're really best off just letting your RDBMS take care of it..
After entering data in html form while clicking on button to add the data in the database, I want to check whether the user already exists in the database. I am using php v5.3.5 and mysql v5.5.8.
Data is stored in 2 tables simultaneously named person and other and there is no primary key(in both columns) since there is no column which can be treated as primary key
Can any one help me how to do that??
Code is::
$sqlComm="Insert into person(Name,father_name,date_birth,
gender,Res_Address,Mobile_no)
values('$name','$fatherName','$dob',
'$gender1','$resAddress','$mobileNo')";
$sql="insert into other_staff(p_id,employer,off_ph_no)
values('$pId','$employer1','$phOffice')";
Id is automatically generated for each person which is retrieved and stored in other table as p_id.
combination of name,father_name,date_birth,employer can be made unique..
It seems like none of the fields suggested can be a primary key, any of them or a combination of them cannot uniquely identify a person. It's a really strange database design and I urge you to check your database design.
You will have to a search by doing a separate select query to find if the user exists. Also Ensure both the statements are executed inside a transaction.
You will have to think about what makes a person unique for your schema/application. Changing the mobile number probably does not make one a new person, but am i the same as an existing person, if we share the name, father_name, date_birth and gender? If so, make that a unique key and you will have something your database can tell you, that it already exists. Just in case you did not already know: keys can span multiple columns.
Dispite with a bad schema, we can find a way(given below) to check weather a user exist or not. BUT I think you also want to check second table THAT with particular user there is an employer or not. Then here is problem in your database cause there is no column in PERSON or OTHER_STAFF's table which can tell us the Particular employer of a specific user in PERSON table
Solution: But for this condition you can use cross join to get nearly correct result:
if($result=mysql_query("SELECT 1 FROM person p CROSS JOIN other_staff e WHERE p.name='$name' AND p.father_name='$father_name' AND p.date_birth='$dob' AND p.gender='$gender1' AND p.Res_Address='$resAddress' AND p.Mobile_no='$mobileNo' AND e.employer='$employer1' AND e.off_ph_no='$phOff';")){
if(mysql_fetch_array($result)){
//exist
}else{
//not exist
}
}
Suggestion: Next time store auto generated id in PERSON and OTHER STAFF table BUT for this project- If you can store p_id in PERSON table then this query will return 1 on exist, otherwise null(same in above):
$sql="SELECT 1 FROM person p LEFT JOIN other_staff e ON p.p_id=e.p_id WHERE p.name='$name' AND p.father_name='$father_name' AND p.date_birth='$dob' AND p.gender='$gender1' AND p.Res_Address='$resAddress' AND p.Mobile_no='$mobileNo' AND e.employer='$employer1' AND e.off_ph_no='$phOff';";
Hello my question is if it is better to have a temporary_users table in my mySQL DB for those users who did not verify by email their account yet. If a user is verified then his data is copied into the users table.
Otherwise, all users, verified or not, will be saved in users table where there will be a new column with a random number. When the user is verified, that value will erased meaning that he is ok to login.
In the future I will create a forgot password function with the same structure as you suggest me.
What is the best method to have ?
Store all users in a single table, and store validation/not-validated state with each record. Whether you add a is_validated column, or simply store a unique token and set it to null for validated users is up to you.
Duplicating an entire table for the sake of adding a single column of data is not a very good practice, and it will be unwieldy; You want to be able to find the user based on their login credentials, and tell them their account is not yet activated. To do this with two tables will require two queries.
It's best to use a column in your main table as a flag for "verified" and "not verified".
When the user registers, insert their info into the database and set the "verified" colunmn to something representational of "not-verified" like a 0.
Once they verify, update your verified column for that user account to something representational of "verified" like a 1.
It is a waste of resources and extra database queries to create a brand new table for temporary users when it is more efficient to simply have a column that represents the users status, like "verified".
You can take this even further and instead have a "status" column for each user. Create a key of values that represent the users state of being, for example:
0 - Created, not verified
1 - Verified
2 - Inactive / Disabled account
3 - Banned
etc..
This can all be controlled by using one column to control the state of the user. It is absolutely un-necessary to have a seperate table for one state of being when you can use one column on the record itself to control as many states of being as you want.
My db table looks like this pic. http://prntscr.com/22z1n
Recently I've created delete.php page. it works properly but when i deleted 21th user next registered user gets 24th id instead of 21.
Is it possible to put newly registered users info to first empty row? (In this situation 21th row)
In my registration form, newly registering user can write names of existing users, and be friends with them after registration. For this friendship i have another table that associates id of newly registered user and existing user.
For this purpose i'm using mysql_insert_id during registration to get id for new user. But after deletion of 21th row during nex registration process mysql_insert_id gave me number 21. but stored in 24th row. And put to associations table 21 for new user. I wanna solve this problem
When you use an autoincrement id column, the value that the next entry will be assigned will not be reduced by deleting an entry. That is not what an autoincrement column is used for. The database engine will always increment that number on a new insert and never decrement that number on a delete.
A MySQL auto_increment column maintains a number internally, and will always increment it, even after deletions. If you need to fill in an empty space, you have to handle it yourself in PHP, rather than use the auto_increment keyword in the table definition.
Rolling back to fill in empty row ids can cause all sorts of difficulty if you have foreign key relationships to maintain, and it really isn't advised.
The auto_increment can be reset using a SQL statement, but this is not advised because it will cause duplicate key errors.
-- Doing this will cause problems!
ALTER table AUTO_INCREMENT=12345;
EDIT
To enforce your foreign key relationships as described in the comments, you should add to your table definition:
FOREIGN KEY (friendid) REFERENCES registration_table (id) ON DELETE SET NULL;
Fill in the correct table and column names. Now, when a user is deleted from the registration, their friend association is nulled. If you need to reassociate with a different user, that has to be handled with PHP. mysql_insert_id() is no longer helpful.
If you need to find the highest numbered id still in the database after deletion to associate with friends, use the following.
SELECT MAX(id) FROM registration_table;
Auto increment is a sequence key that's tracked as part of the table. It does not go back when you delete a row.
Easily, no. What you can do (but I don't suggest doing) is making an SQL function to determine the lowest number that isn't currently occupied. Or you can create a table of IDs that were deleted, and get the smallest number from there. Or, and this is the best idea, ignore the gaps and realize the database is fine.
What you want to do is achievable by adding an extra column to your table called something like user_order. You can then write code to manage inserts and deletions so that this column is always sequential with no gaps.
This way you avoid the problems you could have messing around with an auto_increment column.
It's not a good practice to reset auto_increment value, but if you really need to do it, so you can:
ALTER TABLE mytable AUTO_INCREMENT = 1;
Run this query after every delete. Auto_increment value will not be set to 1, this will set the lowest possible value automatically.
I'm used to building websites with user accounts, so I can simply auto-increment the user id, then let them log in while I identify that user by user id internally. What I need to do in this case is a bit different. I need to anonymously collect a few rows of data from people, and tie those rows together so I can easily discern which data rows belong to which user.
The difficulty I'm having is in generating the id to tie the data rows together. My first thought was to poll the database for the highest user ID in existence, and write to the database with user ID +1. This will fail, however, if two submissions poll the database before either of them writes to it - they will each share the same user ID.
Another thought I had was to create a separate user ID table that would be set to auto-increment, and simply generate a new row, then poll that table for the id of the last row created. That also fails for the same reason as above - if two submissions create a row before either of them polls for the latest user ID, then they'll end up sharing an ID.
Any ideas? I get the impression I'm missing something obvious.
I think I'm understanding you right; I was having a similar issue. There's a super handy php function, though. After you query the database to insert a new row and auto-incrementing their user ID, do:
$user_id = mysql_insert_id();
That just returns the auto-increment value from the previous query on the current mysql connection. You can read more about it here if you need to.
You can then use this to populate the second table's data, being sure nobody will get a duplicate ID from the first one.
You need to insert the user, get the auto-generated id, and then use that id as a foreign key in the couple of rows you need to associate with the parent record. The hat rack must exist before you can hang hats on it.
This is a common issue, and to solve it, you would use a transaction. This gives you the atomic idea being being able to do more than one thing, but have it tied to either a success or fail as a package. It's an advanced db feature, and does require awareness of some more advanced programming in order to implement it in as fault-tolerant a manner as possible.