PHP Create DB/Table


A database holds one or more tables.


Create a Database

The CREATE DATABASE statement is used to create a database table in MySQL.

We must add the CREATE DATABASE statement to the mysqli_query() function to execute the command.

The following example creates a database named “my_db”:

<?php
$con=mysqli_connect(“example.com”,”peter”,”abc123″);
// Check connection
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}

// Create database
$sql=”CREATE DATABASE my_db”;
if (mysqli_query($con,$sql))
{
echo “Database my_db created successfully”;
}
else
{
echo “Error creating database: ” . mysqli_error($con);
}
?>

 


Create a Table

The CREATE TABLE statement is used to create a table in MySQL.

We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.

The following example creates a table named “Persons”, with three columns: “FirstName”, “LastName” and “Age”:

<?php
$con=mysqli_connect(“example.com”,”peter”,”abc123″,”my_db”);
// Check connection
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}

// Create table
$sql=”CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)”;

// Execute query
if (mysqli_query($con,$sql))
{
echo “Table persons created successfully”;
}
else
{
echo “Error creating table: ” . mysqli_error($con);
}
?>

Leave a comment