WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Create a MySQL Database

Datastore has one or more tables.

You need CREATE permission to create or delete MySQL database.


Use MySQLi and PDO to create a MySQL database

CREATE DATABASE statement is used to create a database in MySQL.

In the following example, a database named "myDB" is created:

Instance (MySQLi-Object Oriented)

<?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Detect 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(); ?>


Note: When you create a new database, you must specify three parameters for the mysqli object (servername, username and password).

Tip: If you use a different port (default is 3306), an empty string for the database parameters, such as: new mysqli ( "localhost", "username", "password", "", port)

Examples (MySQLi Procedural)

<?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = mysqli_connect($servername, $username, $password); // Detect connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>

Note: The following use PDO instance creates a database myDBPDO :

Examples

use PDO:

<?php
$servername 
"localhost";
$username "username";
$password "password";

try {
    
$conn = new PDO("mysql:host=$servername"$username$password);

    
// Set up PDO Error mode is abnormal
    
$conn->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
    
$sql "CREATE DATABASE myDBPDO";

    
// use exec() ,Because no result is returned
    
$conn->exec($sql);

    echo 
"Database created successfully<br>";
}
catch(
PDOException $e)
{
    echo 
$sql "<br>" $e->getMessage();
}

$conn null;
?>

Tip: The biggest benefit of using PDO is that you can use exception classes to solve problems in the database query process. solving issues. If an exception occurs in the try {} block, the script stops executing and jumps to the first catch () {} block to execute the code. In the code block captured above, we output SQL statements and generate error messages.