PHP MySQL Create Database

This article will provide you with a step-by-step guide on PHP MySQL create database. Upon completion of this article, you will be able to manage and create MySQL databases through PHP.

PHP MySQL create database doesn’t take a lot of time and effort, and it can be accomplished with a few lines of code at most.

There can be one or more tables in a database. In order to create or delete a MySQL database, you will need special privileges known as CREATE privileges.



Why Create a MySQL Database with PHP?

Creating a MySQL database with PHP allows you to store and retrieve data from your web application.

This is useful for a wide range of applications, including e-commerce sites, social networks, and online forums.


PHP MySQL Create Database

Now that we have a basic understanding of why we might want to create MySQL database with PHP, let’s take a look at the steps involved in creating a MySQL database with PHP.

Step1 – Connect to MySQL

The first step in creating a MySQL database with PHP is to establish a connection to the MySQL server. This can be done using the mysqli_connect() function, which takes four parameters: the server name, the username, the password, and the database name.

// Connect to MySQL
$conn = mysqli_connect("localhost", "username", "password", "database_name");

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

Step2 – Create a Database

Once we have established a connection to the MySQL server, we can create a new database using the mysqli_query() function.

This function takes two parameters:

  • The connection to the MySQL server.
  • The SQL statement to execute.
// Create a new database
$sql = "CREATE DATABASE my_database";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

Step3 – Close the Connection

Once we have created the database, we can close the connection to the MySQL server using the mysqli_close() function.

// Close the connection
mysqli_close($conn);

MySQL Database Through MySQLi and PDO

Creating a database in MySQL can be done by using the CREATE DATABASE statement.

Following are a few examples of creating a database called “mrx_test_db” as shown below:

Below is an example using MySQLi’s Object-Oriented method:

<?php
$servername = "localhost";
$username = "my_user";
$password = "my_pass";

// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Creating database
$sql = "CREATE DATABASE mrx_test_db";
if ($conn->query($sql) === TRUE) {
echo "Database successfully created";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Remember: When you create a new database, on the mysqli object, you should specify only the first three arguments that you will provide, which are servername, username and password).
Hint: You can use an empty string in the database-name argument if you have to use a specific port, such as: new mysqli(“localhost”, “username”, “password”, “”, port).

Below is an example using MySQLi’s Procedural method:

<?php
$servername = "localhost";
$username = "my_user";
$password = "my_pass";

// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Creating database
$sql = "CREATE DATABASE mrx_test_db";
if (mysqli_query($conn, $sql)) {
echo "Database successfully created";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Here is an example of how to create a database in PHP using a PDO module called “mrx_test_dbPDO ”:
<?php
$servername = "localhost";
$username = "my_user";
$password = "my_pass";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// Specify the exception error mode in the PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE mrx_test_dbPDO"; // Due to the fact that no results are returned, use exec() instead
$conn->exec($sql);
echo "Database successfully created";
}
catch (PDOException $e) {
echo $sql . " " . $e->getMessage();
}
$conn = null;
?>

Example Explanation

The above example shows, how to create a MySQL database using PHP and PDO (PHP Data Objects).

Here’s a breakdown of what each line of code does:

  1. $servername = “localhost”;: This sets the hostname of the MySQL server.
  2. $username = “my_user”;: This sets the MySQL username that the PHP script will use to connect to the database.
  3. $password = “my_pass”;: This sets the password for the MySQL user specified in the previous line.
  4. try { … } catch (PDOException $e) { … }: This creates a try-catch block to handle any exceptions that may occur while connecting to the database or executing SQL queries.
  5. $conn = new PDO(“mysql:host=$servername”, $username, $password);: This creates a new PDO object that represents a connection to the MySQL server using the credentials specified in the previous lines of code.
  6. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);: This sets the error mode for the PDO object to throw an exception if there is an error.
  7. $sql = “CREATE DATABASE mrx_test_dbPDO”;: This sets the SQL query to create a new database named “mrx_test_dbPDO”.
  8. $conn->exec($sql);: This executes the SQL query using the exec() method of the PDO object.
  9. echo “Database successfully created”;: If the database was created successfully, this line will be executed and the script will output “Database successfully created” to the browser.
  10. catch (PDOException $e) { echo $sql . ” ” . $e->getMessage(); }: If an exception is caught in the try block, this line will be executed and the error message will be displayed to the browser.
  11. $conn = null;: This closes the connection to MySQL.
Hint: The best part about PDO is its exception class, with which we can handle any errors that may occur during the execution of our database queries. The script is stopped from executing when a try block is reached, and the script immediately jumps into a catch block if an exception is thrown within the try block. Whenever an error is generated by the SQL statement, we echo it in the catch block and the error message is displayed.

Please subscribe to our newsletter below in order to stay up to date with all the latest developments in PHP and MySQL.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *