PHP Create a MySQL Database
To create a MySQL database using PHP, you typically don't use PHP directly for this purpose; instead, you'd use a MySQL client such as phpMyAdmin or the MySQL command-line interface. However, you can use PHP to execute SQL queries that create databases.
Create a MySQL Database Using MySQLi and PDO
The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named "myDB":
Using MySQLi:
<?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Check 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(); ?>You can click on above box to edit the code and run again.
Output
Welcome to Codelines!
Using PDO:
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Create database $sql = "CREATE DATABASE myDB"; // use exec() because no results are returned $conn->exec($sql); echo "Database created successfully"; } catch(PDOException $e) { echo $sql . "You can click on above box to edit the code and run again.
" . $e->getMessage(); } $conn = null; ?>
Output
Welcome to Codelines!