How to Add a Primary Key to a Column of a MySQL Table Using PHP 


               


How to Add a Primary Key to a Column of a MySQL Table Using PHP



PHP







In this article, we show how to add a primary key to a column of a MySQL database using PHP.

Usually at least one column of a MySQL table should have at least one primary key, usually this is the ID column.

When a column is made to be a primary key, this signifies that that each row of the column mis forced to be NOT NULL and each row must have a unique value.

So a row of a column must have a value in it; it cannot be NULL. And each value in a row must be unique. This means that no values can duplicated.

Again, this fits very well, such as in an example as the ID column. You want each row to have a value and the value must be unique.

We make a column a primary key in a MySQL table by using PHP to write the MySQL query to make the the column a primary key.

The general MySQL code to make a column a primary key is shown below.





So the above is the MySQL code to make a column a primary key.

We'll now show how to tie this in with the full PHP code to make the column a primary key.



So, first, we must connect to the database.

After this, we create a $createtable variable which creates a table named customers.

After this, we create the line, PRIMARY KEY (ID). This makes the ID column a primary key.


How to Make Multiple Columns of a MySQL Table a Primary Key

So, in the above code, we make a single column the ID column.

In other instances, it may be necessary to make multiple columns a primary key.

More than one column can be a primary key. And, in certain instances, you may need more than one column to be a primary key.

For example, let's say we have a MySQL table that holds customer information. Each customer has a customerID and an orderID for when the customer orders something.

You may want each value entered into this column to be unique, because 2 customers can't have the same customerIDs and 2 customers cannot have the same orderIDs when they order something. The row also must be entered into; thus it must be NOT NULL.

Therefore, it is the perfect fit for being a primary key.

So this is how the $createtable varies above. It is the only thing that changes in the code above.



So in this code, we simply have to change the $createable variable.

We now have the customerID and orderID as 2 primary keys.

If you wanted to make more columns primary keys, you would just have to add them to the PRIMARY KEY line.




Related Resources

How to Add a Column to a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Concatenate Column Values in MySQL Using PHP

HTML Comment Box is loading comments...