php-mysqlHow to create a database in a MySQL database using PHP?
Creating a database in a MySQL database using PHP is a simple process. The following example code will create a database called my_db
:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE my_db";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
The output of the example code will be:
Database created successfully
The code consists of the following parts:
- Establishing a connection to the MySQL server using
$conn = new mysqli($servername, $username, $password)
- Creating the database using
$sql = "CREATE DATABASE my_db"
- Checking if the database was created successfully using
if ($conn->query($sql) === TRUE)
- Closing the connection using
$conn->close()
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...