How to create a table in MySQL?
We can use the “CREATE TABLE” statement to create a table in MySQL.
A database table has its own name and it must be unique also it has consisted of columns and rows. A table creation command requires three things:
- Name of the table
- Names of fields
- Definitions for each field
Syntax
1 |
CREATE TABLE table_name (column_name column_type); |
Here, we will create a table named “student” in the database.
1 2 3 4 5 6 |
CREATE TABLE student( student_id INT NOT NULL AUTO_INCREMENT, student_firstname VARCHAR(50) NOT NULL, student_surname VARCHAR(75) NOT NULL, PRIMARY KEY (student_id) ); |
Creating Tables Using PHP Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php //Your MySQL databse settings $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "LEARNING"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE TABLE student( student_id INT NOT NULL AUTO_INCREMENT, student_firstname VARCHAR(50) NOT NULL, student_surname VARCHAR(75) NOT NULL, PRIMARY KEY (student_id) )"; if ($conn->query($sql) === TRUE) { echo "Table created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?> |
What is Next?
In the next section, you will learn how to drop a table in MySQL.
* Please do let us know your views on this article and what type of articles would you are interested to read.
Widget not in any sidebars