How can I alter a table to include a primary key in MySQL?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
APD1993
Forum Newbie
Posts: 10
Joined: Sat Mar 03, 2012 4:47 pm

How can I alter a table to include a primary key in MySQL?

Post by APD1993 »

Hi,

I want to be able to add a primary key to a table through altering the table. At the moment, I am using coding such as:

USE test3;
ALTER table users ->ADD primary key (uname);


But I get told: No database selected

Does anyone know how to fix this?

Any help is appreciated :)
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: How can I alter a table to include a primary key in MySQ

Post by social_experiment »

Are you using php to do this? If so can you paste the code you are using
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
APD1993
Forum Newbie
Posts: 10
Joined: Sat Mar 03, 2012 4:47 pm

Re: How can I alter a table to include a primary key in MySQ

Post by APD1993 »

How come I need to give PHP for a MySQL question? :)
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How can I alter a table to include a primary key in MySQ

Post by Celauran »

APD1993 wrote:How come I need to give PHP for a MySQL question? :)
Why are you posting an SQL question in the PHP forum, then?

Code: Select all

ALTER TABLE table_name ADD PRIMARY KEY(`field_name`)
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: How can I alter a table to include a primary key in MySQ

Post by social_experiment »

@APD1993 Your innitial question, although descriptive about the problem you are having, was vague about how you are using the code. Are you entering it via phpmyadmin, via a php script? No database selected means you didn't select a database; whatever method you are using you first have to select a database :|
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply