How to Create a Table in PHP
In PHP, you can create a new table using the CREATE TABLE statement. The basic syntax is as follows:
CREATE TABLE table_name (
column_name data_type [constraint],
...
);
Explanation:
- table_name: The name of the table to be created.
- column_name: The name of a column in the table.
- data_type: The data type of the column, such as INT, VARCHAR, or DATE.
- constraint: Optional constraints to define rules for the column, such as NOT NULL, UNIQUE, or PRIMARY KEY.
Example
Below is an example of creating a table named users with three columns: id, name, and email:
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL
);
Explanation of the example:
- The id column is an auto-increment integer primary key, automatically generating a unique ID for each row.
- The name column is a string of up to 255 characters and cannot be empty.
- The email column is a string of up to 255 characters and must be unique.
After executing this statement, a new table named users will be created with the specified columns and constraints.