Php CREATE DB
The CREATE DATABASE
statement is used to create a new database in MySQL. In PHP, we can create a database using the following syntax:
Syntax
$conn = mysqli_connect($servername, $username, $password);
$sql = "CREATE DATABASE dbname";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
Example
Let's see an example to create a database named my_database
:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE my_database";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Output
If the above code is executed successfully, then you will see the following output:
Database created successfully
Explanation
In the above example, we have used mysqli_connect()
function to connect to MySQL server. After establishing the connection, we have used the mysqli_query()
function to execute the CREATE DATABASE
statement.
Use
The CREATE DATABASE
statement is used to create a new database in MySQL. This statement can be used in PHP to create a database for a web application.
Important Points
- If the database already exists, then you will get an error.
- The user must have privileges to create a database in MySQL.
- The
mysqli_query()
function is used to execute the query in PHP.
Summary
- The
CREATE DATABASE
statement is used to create a new database in MySQL. - PHP can be used to create a database using the
mysqli_query()
function. - If the database already exists, then an error will be thrown.