Insert into database with unique/primary key - php

I'm using a simple form to insert posts to my MySQL database, I want each post to have an unique ID but don't know the proper way to do it.
I already created a column named "PID" and set it as a primary key however I don't know how to make each INSERT generate the PID. The only way I can think of is to make PHP look for the higher PID and add +1 to it. Is there an easier way to do it? Thanks

If you manage your MySQL database with a software like e.g. phpMyAdmin then you can set the "auto_increment" flag on this column.
Else you have to set it manually as described in this manual.

You need to set PID to be an Identity field
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
CREATE TABLE posts(
PID MEDIUMINT NOT NULL AUTO_INCREMENT,
someotherfield CHAR(30) NOT NULL,
...etc...,
PRIMARY KEY (PID)
)

You can make the field 'auto_increment'. That way, MySQL creates a unique id for each record. You can use mysql_insert_id to get the last inserted id.

Make the PID column auto_increment

Set that PID field to AUTO_INCREMENT. In PHPMyAdmin there's a INDEX field you can set to AI, if I remember correctly.
Using AUTO_INCREMENT

Use auto_increment on the field.
E.g. pid int primary key auto_increment

You can use auto increment on Id field.

Make the field auto_increment in your mysql table.

Related

Generate unique id for user when they will register in Mysql Database

I am trying to create a login-registration system with PHP mysql and HTML. I want that, when user will register with his email and password, an unique ID will generate into database only for him. Example: when a user register an unique number auto create like 1, 2, 3, 4... I want an unique ID of 5 digits instead of 1, 2, 3 auto increment number.
Make your id (primary) column auto-increment.
Also, add a record with id 10000 either manually or with code.
Next record added will have id 10001.
This solves your question.
To start with an AUTO_INCREMENT value other than 1, set that value with CREATE TABLE or ALTER TABLE, like this:
ALTER TABLE tbl AUTO_INCREMENT = 100000;
You can define auto increment value when you create table.
Fist make that field primary key and assign auto increment value to your desire number.
CREATE TABLE IF NOT EXISTS tableName (
id int(11) NOT NULL PRIMARY KEY,
.........
) ENGINE=InnoDB AUTO_INCREMENT=10001 DEFAULT CHARSET=utf8;
I hope you need to do this with your phpmyadmin UI. So go to phpmyadmin and follow the steps below.
(If you have already selected autoincrement field start from step 4).
1. In "Structure" tab of your table
2. Click on edit on column you want auto_increment
3. under "Extra" tab choose "auto_increment"
4. then go to "Operations" tab of your table
5. Look for "Table options" -> auto_increment Then type 10000
You can disable the auto increment and use uniqid() function then save it in the ID Section.
For this you can use ZEROFILL it will prepand required 0's to number so try this query:
ALTER TABLE `tbl_teacher` CHANGE `id` `id` INT(11) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT;
;)

How to ensure unique number sequentially in php using mysql?

I am developing an web application where I have to give every new registrant a serial number. The main issue is with 'how to ensure uniqueness?'. I have searched through the different functions available with mysql and found mysql_insert_id() to be the fittest solution here. But before I run towards it, I need to know whether this function is thread-free. To more precise, say there are two users sitting at two different terminals and submits the registration form synchronously. Will they both get the same id out of the execution of the function mysql_insert_id()? Otherwise, my project will spoil. Please help. If I could not clear my point, please comment. Thanks in advance.
here is detailed solution
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
If you have an id column on your table in your database and that column is set to be the primary key that will be enough. Even if 2 people will submit the form at the same the ids will be unique.
id column could be defined like this
ADD PRIMARY KEY (`id`)
id` int(11) NOT NULL AUTO_INCREMENT
Alternatively, you can use the UUID() function in mysql.
A UUID is designed as a number that is globally unique in space and
time. Two calls to UUID() are expected to generate two different
values, even if these calls are performed on two separate computers
that are not connected to each other.
mysql> SELECT UUID();
-> '6ccd780c-baba-1026-9564-0040f4311e29'
For further details : http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

MYSQL QUERY to retrieve the data

I have the following schema with the following attributes:
USER(TABLE_NAME)
USER_ID|USERNAME|PASSWORD|TOPIC_NAME|FLAG1|FLAG2
I have 2 questions basically:
How can I make an attribute USER_ID as primary key and it should
automatically increment the value each time I insert the value into
the database.It shouldn't be under my control.
How can I retrieve a record from the database, based on the latest
time from which it was updated.( for example if I updated a record
at 2pm and same record at 3pm, if I retrieve now at 4pm I should get
the record that was updated at 3pm i.e. the latest updated one.)
Please help.
I'm assuming that question one is in the context of MYSQL. So, you can use the ALTER TABLE statement to mark a field as PRIMARY KEY, and to mark it AUTOINCREMENT
ALTER TABLE User
ADD PRIMARY KEY (USER_ID);
ALTER TABLE User
MODIFY COLUMN USER_ID INT(4) AUTO_INCREMENT; -- of course, set the type appropriately
For the second question I'm not sure I understand correctly so I'm just going to go ahead and give you some basic information before giving an answer that may confuse you.
When you update the same record multiple times, only the most recent update is persisted. Basically, once you update a record, it's previous values are not kept. So, if you update a record at 2pm, and then update the same record at 3pm - when you query for the record you will automatically receive the most recent values.
Now, if by updating you mean you would insert new values for the same USER_ID multiple times and want to retrieve the most recent, then you would need to use a field in the table to store a timestamp of when each record is created/updated. Then you can query for the most recent value based on the timestamp.
I assume you're talking about Oracle since you tagged it as Oracle. You also tagged the question as MySQL where the approach will be different.
You can make the USER_ID column a primary key
ALTER TABLE <<table_name>>
ADD CONSTRAINT pk_user_id PRIMARY KEY( user_id );
If you want the value to increment automatically, you'd need to create a sequence
CREATE SEQUENCE user_id_seq
START WITH 1
INCREMENT BY 1
CACHE 20;
and then create a trigger on the table that uses the sequence
CREATE OR REPLACE TRIGGER trg_assign_user_id
BEFORE INSERT ON <<table name>>
FOR EACH ROW
BEGIN
:new.user_id := user_id_seq.nextval;
END;
As for your second question, I'm not sure that I understand. If you update a row and then commit that change, all subsequent queries are going to read the updated data (barring exceptionally unlikely cases where you've set a serializable transaction isolation level and you've got transactions that run for multiple hours and you're running the query in that transaction). You don't need to do anything to see the current data.
(Answer based on MySQL; conceptually similar answer if using Oracle, but the SQL will probably be different.)
If USER_ID was not defined as a primary key or automatically incrementing at the time of table creation, then you can use:
ALTER TABLE tablename MODIFY USER_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
To issue queries based on record dates, you have to have a field defined to hold date-related datetypes. The date and time of record modifications would be something you would manage (e.g. add/change) based on the way in which you are accessing the records (some PHP-related way? it's unclear what scripts you have in play, based on your question.) Once you have dates in your records you can ORDER BY the date field in your SELECT query.
Check this out
For your AUTOINCREMENT, Its a question already asked here
For your PRIMARY KEY use this
ALTER TABLE USER ADD PRIMARY KEY (USER_ID)
Can you provide more information. If the value gets updated you definitely do NOT have your old value that you entered at 2pm present in the dB. So querying for it will be fine
You can use something like this:
CREATE TABLE IF NOT EXISTS user (
USER_ID unsigned int(8) NOT NULL AUTO_INCREMENT,
username varchar(25) NOT NULL,
password varchar(25) NOT NULL,
topic_name varchar(100) NOT NULL,
flag1 smallint(1) NOT NULL DEFAULT 0,
flag2 smallint(1) NOT NULL DEFAULT 0,
update_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
For selection use query:
SELECT * from user ORDER BY update_time DESC

how to do auto increment?

I know this may be a stupid question to ask but I have really forgotten how to do it.
How do I auto increment a photo ID whenever a record is inserted into mySQL database ?
I would want it to start with 1 for the first record and then subsequently +1 for the next. Thanks
I have set my database column photoID to PK, NN and AI.
The MySQL documentation for AUTO_INCREMENT has a nice, clear example. In brief, if your field has been defined as auto incrementing, e.g.:
CREATE TABLE tablename (
photoID INT NOT NULL AUTO_INCREMENT,
anotherField VARCHAR(50),
....
);
then when you do an INSERT, if you do not specify a value for photoID, the value will auto increment (if you explicitly specify a value of NULL or 0 in the values list, the value will also auto increment):
INSERT INTO tablename (anotherField) VALUES ('something');
A SELECT would result in photoID value of 1, anotherField value of something.
Set the 'photoID' column on the database to 'autoincrement' using phpmyadmin. It is one of the options on it. It will automatically then do it for you.
CREATE TABLE foto ( ID int auto_increment, UNIQUE(ID) );

autoincrement as primary key causing duplicate entries

I want an id and name to be primary key for my table. I want to increment id with every insert, so i set it to auto_increment. The problem is when i insert into table a new entry with same name, it inserts it with a new id and there are duplicate entries with same name and different ids. I don't want to search the table beforehand to see if there is any entry beforehand. Please help me how to correct this problem.
I think you have done something like this
CREATE TABLE table1
id unsigned integer autoincrement,
name varchar,
....
primary key (id,name)
This primary key does not select on unique name, because the autoincrement id will always make the key as a whole unique, even with duplicate name-fields.
Also note that long primary keys are a bad idea, the longer your PK, the slower inserts and selects will execute. This is esspecially bad on InnoDB, because the PK is included in each and every secondary key, ballooning your index files.
Change it to this
CREATE TABLE table1
id unsigned integer autoincrement primary key,
name varchar,
....
unique index `name`(name)
If you want it to be unique by name, you need to add a unique index on the name field, and then you can use the mysql syntax for on duplicate key: mysql reference for on duplicate key
You could apply a unique index to your name field, or if you're storing people, allow duplicate names.
Add UNIQUE(your_column_name) where you should replace your_column_name with the column in your database.

Categories