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


In this article, we show how to make a column of a MySQL table unique using PHP.

When a column is made unique, this means that no 2 values in the column can be the same. Each value must be unique in each row.

So if one user enters into an email, for instance,, another user cannot enter in the same email abc@gmail.

Each value must be unique.

Making a column is very commonplace and valuable for many things.

One example is an email address. 2 different users can't have the same email address. Therefore, if a user types in an email address already in the table, the MySQL won't accept it. It will give an error that the entry is a duplicate and the new data will not be added to the MySQL table.

So having a unique column is very valuable for any data that can't be a duplicate. Examples are email, cell phone numbers, social security numbers, credit card numbers, etc.

So making a column unique has plenty of application.

So below a create a table with a first name, last name, and email column. The email column is made unique.

So, first, we must connect to the database.

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

create an ID, firstname, lastname, and email column.

To make the email column is made unique by adding UNIQUE to the definition of the declaration. This makes the email column unique. It's very simple.

How to Make an Existing Column Unique

So above we created a table and made a column unique.

How can an existing column be made UNIQUE when the table has already been made?

The following PHP code below modifies the existing email column to be unique.

So the PHP code above makes the email column unique.

The SQL MODIFY keyword allows a column to be modified. When modifying a column, put the full definition of the column. So we declare the email column to be of type VARCHAR(50), NOT NULL, and UNIQUE.

So this is how a column of an existing table can be made unique.

Related Resources

How to Add a Column to a MySQL Table Using PHP

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

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

HTML Comment Box is loading comments...