Jump to content

Primary Key - A problem understanind its Function!


npsari

Recommended Posts

I created a database...

 

Now, I am about to create a table

 

It says I have to create a Primary key for the Table!

 

I dont understand what is the point of this primary key

 

The user has 3 fields to fill-in  in my Form

Name:

Occupation:

Age:

 

So, Do i have to create a new field (in the HTML Form) which asks the user to insert a unique ID (As this unique key)

 

Can someone please explain how this ID key works

Link to comment
Share on other sites

Each record must have a unique identifier (or the dbms does not know which one you want to update or delete)  but it doesn't have to be an ID field. For example, if it's person then you could use their National Insurance Number/Social Security number as the PK since it is unique and you are storing it already. Or, for an invoice table, use the invoice number.

 

In your table none of the fields would be unique (name, occupation, age) as any could reasonably be duplicated. Therefore the easiest way in that case is to create an auto-incrementing id as the PK

Link to comment
Share on other sites

So who gives the value of this Key

Does it happen automatically?

 

or does the user Fill it in?

 

What if I called the key ID, therefore, the table has 4 rows

 

ID:

Name:

Accupation:

Age:

 

And the user only submitted the last 3 (Name, occupation, ID) in the HTML form

 

What happens?

Link to comment
Share on other sites

if you define your table with, say,

CREATE TABLE mytablename (
  ID int not null auto_increment primary key,
  name varchar (50),
  occupation varchar (50),
  age tinyint
)

 

The the user need not be aware that the key exist. They enter name, occupation and age and you insert those values

 

INSERT INTO mytablename (name, occupation, age) VALUES ('$name', '$occupation', '$age')

 

Note there is no mention of the id field. Mysql takes care of it for you, generating the next value as each row is added.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.