English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to create a database in MySQL using PHP.
Now that you have learned how to open a connection with the MySQL database server, in this tutorial, you will learn how to execute SQL queries to create a database.
Before saving or accessing data, we need to create a database first.CREATE DATABASEstatement is used to create a new database in MySQL.
Let's use the CREATE DATABASE statement to perform an SQL query. After that, we will execute this SQL query by passing it to the PHP mysqli_query() function to ultimately create the database. The following example creates a database nameddemoDatabase.
<?php /* Attempt to connect to MySQL server. Assume you are running MySQL. Server with default settings (user 'root' without password) */ $link = mysqli_connect("localhost", "root", "); // Check connection if($link === false){ die("Error: Cannot connect. ". mysqli_connect_error()); } //Attempt to create database query execution $sql = "CREATE DATABASE demo"; if(mysqli_query($link, $sql)){ echo "Database created successfully"; } else{ echo "Error: Cannot execute $sql. ". mysqli_error($link); } //Close connection mysqli_close($link); ?>
<?php /* Attempt to connect to MySQL server. Assume you are running MySQL. Server with default settings (user 'root' without password) */ $mysqli = new mysqli("localhost", "root", ""); //Check connection if($mysqli === false){ die("Error: Cannot connect. ". $mysqli->connect_error); } //Attempt to create database query execution $sql = "CREATE DATABASE demo"; if($mysqli->query($sql) === true){ echo "Database created successfully"; } else{ echo "Error: Cannot execute $sql. ". $mysqli->error; } //Close connection $mysqli->close(); ?>
<?php /* Attempt to connect to MySQL server. Assume you are running MySQL. Server with default settings (user 'root' without password) */ try{ $pdo = new PDO("mysql:host=localhost;", "root", ""); //Set PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("ERROR: Could not connect. ". $e->getMessage()); } //Attempt to create database query execution try{ $sql = "CREATE DATABASE demo"; $pdo->exec($sql); echo "Database created successfully"; } catch(PDOException $e){ die("Error: Cannot execute $sql. ". $e->getMessage()); } //Close connection unset($pdo); ?>
Hint:Setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION tells PDO to throw an exception whenever a database error occurs.