The best PHP MySQL Create Database Tutorial In 2024, In this tutorial you can learn
Create a MySQL database using MySQLi and PDO,Examples (MySQLi - Object Oriented),Examples (MySQLi Procedural),Examples,
PHP MySQL Create Database
Database contains one or more tables.
CREATE permission you need to create or delete MySQL database.
Create a MySQL database using MySQLi and PDO
CREATE DATABASE statement is used to create a database in MySQL.
In the following example, we create a database called "myDB" of:
Examples (MySQLi - Object Oriented)
<? Php
$ Servername = "localhost";
$ Username = "username";
$ Password = "password";
// Create connection
$ Conn = new mysqli ($ servername, $ username, $ password);
// Test connection
if ($ conn-> connect_error) {
die ( "Connection failed:" $ conn-> connect_error.);
}
// Create a database
$ Sql = "CREATE DATABASE myDB";
if ($ conn-> query ($ sql) === TRUE) {
echo "Database successfully created";
} Else {
echo "Error creating database:" $ conn-> error;.
}
$ Conn-> close ();
?>
| Note: When you create a new database, you must specify three parameters mysqli objects (servername, username and password).
Tip: If you use a different port (default is 3306), add 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);
// Test connection
if (! $ conn) {
die ( "Connection failed:". mysqli_connect_error ());
}
// Create a database
$ Sql = "CREATE DATABASE myDB";
if (mysqli_query ($ conn, $ sql)) {
echo "Database successfully created";
} Else {
echo "Error creating database:" mysqli_error ($ conn);.
}
mysqli_close ($ conn);
?>
Note: Creating a database "myDBPDO" PDO instance using the following:
Examples
Use PDO:
<? php
$ servername = "localhost";
$ username = "username";
$ password = "password";
try {
$ conn = new PDO ( "mysql : host = $ servername; dbname = myDB", $ username, $ password);
// Set the PDO error mode exception
$ conn -> setAttribute (PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION);
$ sql = "CREATE DATABASE myDBPDO" ;
// Use exec (), because there is no result is returned
$ conn -> exec ($ sql );
echo "database created successfully <br>";
}
catch (PDOException $ e)
{
/en echo $ sql "<br>" $ e -> getMessage ();
}
$ conn = null;
?>
Tip: The biggest advantage of using PDO is that you can use when there is a problem during a database query exception class to handle the problem. If there is an exception try {} block, the script will stop executing and will jump to the first catch () {} code block code execution. In the above code block we capture the output of the SQL statement and generate an error message.