The following code shows an Example of Creating a MySQL Database Table Using PHP.
Here, we need to use the SQL command ‘CREATE TABLE’ and pass it as an argument to the query() function. However, the following code results in a connection error. This is because, we have not specified a database name.
<?php
$server_host="localhost";
$database_user="root";
$password="";
// Connect with MySQL Server
$con1=new mysqli($server_host, $database_user, $password);
// Create a query for database creation
$query="create table course(course_id integer primary key, course_name varchar(6) unique not null, duration integer, credits integer)";
// Execute the query
$b=$con1->query($query);
if($b)
{
echo 'Table Created Successfully!';
}
else
{
echo 'Table could not be created due to error: <br>',$con1->error;
}
// close the connection
$con1->close();
?>
Output
Now, we the name of the database as the fourth parameter of the constructor of the mysqi object. So we get the table created.
<?php
$server_host="localhost";
$database_user="root";
$password="";
// Connect with MySQL Server
$con1=new mysqli($server_host, $database_user, $password, "institute");
// Create a query for database creation
$query="create table course(course_id integer primary key, course_name varchar(6) unique not null, duration integer, credits integer)";
// Execute the query
$b=$con1->query($query);
if($b)
{
echo 'Table Created Successfully!';
}
else
{
echo 'Table could not be created due to error: <br>',$con1->error;
}
// close the connection
$con1->close();
?>
Output
Further Reading
Examples of Array Functions in PHP