Advertisement

Google Ad Slot: content-top

MySQL Create Table

~1 min read · PHP
On this page

Creating a table in MySQL using PHP involves writing a script to establish a database connection and executing a SQL CREATE TABLE query.


A database table has its own unique name and consists of columns and rows.


Create a Table Using MySQLi and PDO


We will create a table named "users", with five columns: "id", "name", "email" and "created_at":


Example (MySQLi Procedural)

Above created table explanation:


Data types are used to specify the type of data that can be stored in a table's column.


You can specify other optional attributes for each column, followed by data type.


  • UNSIGNED: Ensures the value is positive.
  • AUTO_INCREMENT: Automatically increments for each new row.
  • PRIMARY KEY: Makes id the unique identifier for each record.
  • NOT NULL: Ensures the field cannot be empty.
  • UNIQUE: Ensures no duplicate email addresses.
  • DEFAULT CURRENT_TIMESTAMP: Automatically sets the current timestamp when a record is created.
Example (Object-Oriented)
connect_error) { die("Connection failed: " . $conn->connect_error); } // SQL to create table $sql = "CREATE TABLE users ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table 'users' created successfully"; } else { echo "Error creating table: " . $conn->error; } // Close connection $conn->close(); ?>
Example (Procedural Method)