PHP
MySQL creates a database
In the last section, if you successfully connected to the MySQL database, please create the database further in this section.
The data inventory has one or more tables.
You
need CREATE
permissions to create or delete the MySQL database.
Create a MySQL database with MySQLi and PDO
Create DATABASE statements are used to create databases in MySQL.
In the following example, a database named "myDB" is created:
Instances (MySQLi - Object Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
Create a connection
$conn = new mysqli($servername, $username, $password);
Detect the 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 3306), add an empty string to the database parameters, such as: new mysqli ("localhost," "username," "password," "port")
|
Example (MySQLi Process)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
Create a connection
$conn = mysqli_connect($servername, $username, $password);
Detect the 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 uses a PDO instance to create a database "myDBPDO":
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;
dbname=myDB", $username, $password);
Set the PDO error mode to be an exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
Use exec() because no results are 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 handle problems during the database query process. I
f there is an exception to the try snr block, the script stops executing and jumps to the first catch() snr block to execute the code. I
n the block of code captured above, we output SQL statements and generate error messages.
Read about it
When using a MySQL database, you need to be aware of which data types are allowed, please refer to
MySQL Data Types for details.