Create a MySQL Database

You can create a mysql database by using the php script.

Example:

[php]<?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 myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>[/php]

Code explanation:

In the code first, we are connecting php to the server by using server login details.

$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);
}

Once the server is connection we have used the mysql query statement to create a database on the server.

$sql = "CREATE DATABASE myDB";

To verify it we are using if statement. The if statement checks whether the connection to the server is successfully achieved by using the $conn variable. Then it checks the $sql query with the operator identical check === is true. If everything is run ok the echo statement “Database created successfully” is proceed to the browser else the error message “Error creating the database: ” with the connection error. The $conn->error is shown to the browser.

if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

In the end, we are closing the php script with the closing function.

$conn->close();

Related Posts

Leave a Reply