A database has one or more tables.
You need CREATE permission to create or delete MySQL databases.
The CREATE DATABASE statement is used to create a database in MySQL.
In the following example, a database named "myDB" is created:
Note: When you create a new database, you must specify three parameters (servername, username and password) for the mysqli object. 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) |
Note: The following uses the PDO instance to create the database myDBPDO :
Using PDO:
<?php$servername = "localhost" ; $username = "username" ; $password = "password" ;try { $conn = new PDO ( "mysql:host= $servername " , $username , $password ); // Set PDO error mode to exception $conn -> setAttribute ( PDO :: ATTR_ERRMODE , PDO :: 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 handle problems when problems occur during database query. If an exception occurs in the try{ } code block, the script will stop executing and jump to the first catch(){ } code block to execute the code. In the code block captured above we output the SQL statement and generate the error message.