Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP MySQL Create Database

PHP MySQL Create Database


A database holds one or more tables.

You need CREATE privileges to create or delete a MySQL database.


Create MySQL Database Using MySQLi and PDO

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

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

Example (MySQLi - Object-Oriented)

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 | Note: When you create a new database, you must specify three parameters for the mysqli object (servername, username, and password).

 **Tip:** 如果你使用其他端口(默认为3306),为数据库参数添加空字符串,如: new mysqli("localhost", "username", "password", "", port) |

| --- | --- |

Example (MySQLi Procedural)

Note: The following uses a PDO example to create a database myDBPDO :

Example

Using PDO:

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"
" ; } catch( PDOException $e ) {     echo $sql . "
" . $e -> getMessage (); } $conn = null ; ?>

Tip: The biggest advantage of using PDO is that you can use exception classes to handle problems when issues occur during database queries. If an exception occurs in the try{} block, the script stops execution and jumps to the first catch(){} block to execute code. In the caught block above, we output the SQL statement and generate an error message.