PHP : MySQL Create Database

The "CREATE DATABASE db_name" command is used to create a database in MySQL.

To learn more about PHP & MySQL database, we will create a Database. Later we will use it to insert or retrieve data from this database.



Create Database using PHP and MySQL

In this example first, we will create a database server connection (See detail in the previous chapter). Then, we can create a new database using the above command/statement.

query() function is used to performs queries for a database. You can almost run any query on the database using this function. This function will work on the connection object and you can pass a query statement to run on the database. Then, it will perform database query with given connection and return a result.

 * Create Database Connection

$database_server = 'localhost';
$database_username = 'root';
$database_password = '';

// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password);

// If $conn is false, connection is failed
if (!$conn ) {
  die("Failed to connect to MySQL: " . mysqli_connect_error());

// Run database query
$sql = "CREATE DATABASE test_db";
$status = $conn->query($sql);

// If query was successful, it should return true
if ($status) {
  echo "Database created successfully";
} else {
  echo "Error creating database: " . $conn->error;


Description of the above example

  • First, we created a database connection using mysqli_connect() function and assign it to $conn object.
  • Then, we assigned a SQL statement in a variable named $sql.
  • After that, we used query() function in connection object to perform database query.
  • If query executed successfully, it will assign some data into $status variable. If the query was not proper, it will save
    false boolean value to the variable.
  • Now, we will print success or failure messages based on $status variable information.
  • close() function closes a previously created database connection.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.