PHP Basics

PHP MySQLi Create Table

The first job, in php database project can be creating a table. In this article, we will learn how to create a table in mysql database using php and mysqli. (See following table example)

emp_id emp_name emp_age
1 Raj 22
2 Rahul 24
3 Vivek 26
4 Ajay 28
5 Suraj 29

Lets see how can we create a table just like above one.

In the above table, we have three columns.

  • The first column is an id, which is an integer in this case
  • The second column is employee name column which varchar.
  • The third column is employee age column which is integer.

Before creating a table, we must have a clear vision or understanding about all the required columns and its data type. (If any thing goes wrong, we have option to change, but it is wise to be sure everything is at its right place before proceeding further)

When ever we need to create a table using mysqli in python projects, we are bound to follow three steps.

  1. Step 1: Establish Database Connection
  2. Step 2: Create table
  3. Step 3: Close the database connection

Note: Once all the required job is complete, we should immediate close the database connection. Otherwise hackers may take advantage of such situation.

In previous article, I have discussed about database connection establishment.

In this article, just before running the sql command to create table, one more important thing we must have to remember.

I am assuming you are well aware of sql command to create a table, jumping straight to the code.

Remember, in PHP, when ever we want to execute a sql command using mysqli, we must have to call the mysqli_query function which takes two arguments. One is connection and second one is the sql command.

Example

mysqli_query($connection,$sql)

lets implement and create a tabel.

Create a Table

//Step 1

$conn=mysqli_connect(‘localhost’,’root’,”,’employee_db’)

//Step 2

$sql=’create table employee_info(id int primary, emp_name varchar(100),emp_age int)’

if(mysqli_query($conn,$sql)){

echo “Table Created”;

}else{

echo “Table Failed to Create”;

}

///Step 3

mysqli_close($conn)

If I run the above code, employee_info table is created in the database.