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.

Syntax

CREATE DATABASE databasename;


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.

$mysqli_query function is used to performs queries for a database. You can almost run any query on the database using this function. This function takes two arguments. First, you need to pass connection information and then you can pass a query statement to run on the database. Then it will perform query operation and return a result.

<?php
/**
 * 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());
}

echo "Database Connected Successfully.";

?>
<?php
/**
 * 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());
}

echo "Database Connected Successfully.";

?>

Description of the above example

  • First, we created a database connection using
    mysqli_connect() function.
  • Then, we assigned a SQL statement in a variable named
    $sql.
  • After that, we used
    $mysqli_query function to perform above DB statement to create a database.
  • 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.
  • mysqli_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.