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)
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.
- Step 1: Establish Database Connection
- Step 2: Create table
- 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.
lets implement and create a tabel.
Create a Table
$sql=’create table employee_info(id int primary, emp_name varchar(100),emp_age int)’
echo “Table Created”;
echo “Table Failed to Create”;
If I run the above code, employee_info table is created in the database.