how to prevent MySQL primary key from duplication - php

I am creating user detail table in MySQL where user details are stored when user submits registration form.
In my user table user id field is primary key and auto increment.
My application should be used by many users from many locations. Now there is one scenario when it is possible that two user clicks on submit button at same time from anywhere. My primary key is of integer type and has length of 15, but when two user clicks at same time then which user should get first next id. Or it is possible that none of that get registered and get error.
so what can i do in this case

Your mySQL id field is good, so you should have no problem; however, when inserting a new record, then depending on what your insert SQL query looks like, make sure you leave the id undefined, or use something like:
insert into users values(NULL, "blah", "blah")
-where "NULL" is your first column / field.
This will only work the way you expect if the field (column) in place "NULL" is set (when created, or altered) to AUTO INCREMENT.
If these are set, the record id is incremented on each data entry, no matter if it happens at the same time; new records are always queued to be inserted one after the other.

Related

Update MYSQL Table if Name is Already In the DB

I have a database that stores user details, I want users to be able to update their details if their name matches.
Currently I submit details to the database like this:
$sql="INSERT INTO gdpr_info (name, email, phone, comments, phoneout, emailout, postout, phonein, emailin, postin) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."', '".$comments."','".$phoneout."','".$emailout."','".$postout."','".$phonein."','".$emailin."','".$postin."')";
How would I go about updating the user row ONLY if the name matches for example if a user called 'Robbie Fowler' wanted to update his email he would go to the form, type his name and anything else he puts in after would update his row instead of creating a new row.
I've seen the duplicate key option, but on the form there are checkboxes so I'm worried that if I use that most of the forms will have at least one duplicate key due to the checkbox and it will update the wrong row.
Can you specific which column must be duplicated to update the row?
If he is the user want to update his details I guess you the use the mysql update query to update how this will done is
First fetch the user from the db . The user can be the logged in user who wants to update
Then update the email column like this
UPDATE table-name SET column ='.$_POST['newvalue'].' WHERE namecolumn ='.$loggedINuser.';
Or if you want to change the bame as you said in the question with the name input and the new email then
UPDATE table-name SET column ='..$_POST['newvalue'].' WHERE namecolumn ='.$_POST['name'].';
And also I guess there can be only one primary fields in a table so just look for that the You can have multiple unique columns but one primary column (id column is recommended for that )
Hope this will work

Insert multipe rows for the same value - SQL

How can I insert more than one row for the same value
for example, each user has to submit 2 forms so the username is the same in each form but the information is different
I tried to use UPDATE but it removes the ole information and replaces it with the new one while I want to keep both
is there a way to do that?
insert into your_table (username, col2)
values ('user1', 1),
('user1', 2)
Have two tables, 'USERS' and 'FORMSUBMISSIONS'
When a user submits a form for the first time, a new entry is created in the USERS table, which is unique for each user, and would contain information connected to the user.
And whenever a form is submitted (including the first time), an entry is written to the FORMSUBMISSIONS table with the details of that submission, and a foreign key back to USERS.
That's a cleaner data model for this situation. It will also help future queries on the data. If you are limited to a single table for some reason, then successive inserts will work as above, as long as there is no unique key on the USER field.
you can add duplicate data just your primary key can't be duplicated because it causes primary key constraint. so what you can do is have an extra column let's say "ID" make it your primary key. While submitting the row keep on adding ID column's value by one, rest of the data could be same.
It depends on whether your USERNAME column allows duplicates.
If it's the primary key of the table, your table schema doesn't support what you want to do, because PK should be UNIQUE.
If your USERNAME column allows duplicates, you can use INSERT:
declare #username varchar(max) = 'your_username' --declare a variable to use the same username
insert into table_name (username, form_data)
values(#username, 'form_data_1')
,(#username, 'form_data_2')
It also depends on how you're executing the SQL statement. I would definately go and create stored procedure to do this insert.
you can use bulk insert query for that. as suggested by #huergen but make sure that your username or any field that might be in form data does not have UNIQUE key index. you can also add another field that works like PRIMARY key in that table.so many ways to do but it depends upon your requirement.
Use below insert format to get your desired result:
insert into Table_name(Field1, Field2)
SELECT 'user_1', 1 UNION ALL
SELECT 'user_1', 2

Only one user can make changes at a time in a `table` in case of many users [duplicate]

I was just creating a new table using MySQL Query Browser, and noticed there's a tick under Auto Increment Column. How does that work?
When adding to the database programatically, do I just add a number, and then the database automatically increments that number?
Everytime a NEW user registers on my site, I want their Customer ID (integer only) to auto increment, so I don't have to try and randomly generate a unique number.
Can this be done simply?
Thank you!
When adding to the database programatically, do I just add a number, and then the database automatically increments that number?
Yes, that's the way auto_increment works.
The value will be incremented for each new row
The value is unique, duplicates are not possible
If a row is deleted, the auto_increment column of that row will not be re-assigned.
The auto_increment value of the last inserted row can be accessed using the mySQL function LAST_INSERT_ID() but it must be called right after the insert query, in the same database connection
mySQL Reference
1 more,
You can insert your own value also (ie your random value).
Yes. Auto_Increment columns work like they say on the tin. Tips
when INSERT - ing, use NULL or omit the column
Use LAST_INSERT_ID() (or API equivalents) to obtain the last generated value.
for security and business logic reasons, it's usually better form to not directly use a key value for a customer identifier. Consider using Hashed / randomised surrogate customer keys instead.
Ta
Yes, that's the exact purpose of AUTO_INCREMENT. It looks at whatever is the current increment value for that table, and stores that value plus 1 for the new row that comes in, automatically. You can omit that field from your INSERT statements and MySQL will handle it for you for every new row that comes in, giving each row its own unique ID.
When you enable Auto Increment an ID will always get automatically added whenever a new record is made.. Example:
If you have 1 record with ID 1 in your table and you add a new record, the ID will automatically be 2.

Problem with auto-incremented "id" column

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.

Unique Value in MySQL Database

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.

Categories