php
Creating MySQL Database Using PHP
The CREATE DATABASE statement is used to create a database in MySQL

We must add the CREATE DATABASE statement to the mysql_query() function to execute the command.

The following examples create a database named "ftl_db" :
MySQLi - Procedural
<?php

	// variable is yor wish $conn or $ftl or $ftl_connect etc,.
	
	$ftl_connect = mysqli_connect("localhost", "root", "");
	// Check connection
	if (!$ftl_connect) {
		die("Connection failed: " . mysqli_connect_error());
	}
	
	// Create database
	$sql = "CREATE DATABASE ftl_db";
	if (mysqli_query($ftl_connect, $sql)) {
		echo "Database created successfully";
	} else {
		echo "Error creating database: " . mysqli_error($ftl_connect);
	}
	
	mysqli_close($ftl_connect);
?>
MySQLi - Object-Oriented
<?php
	$ftl_connect = mysqli_connect("localhost", "root", "");
	// Check connection
	if ($ftl_connect->connect_error) {
		die("Connection failed: " . $ftl_connect->connect_error);
	} 
	
	// Create database
	$sql = "CREATE DATABASE ftl_db";
	if ($ftl_connect->query($sql) === TRUE) {
		echo "Database created successfully";
	} else {
		echo "Error creating database: " . $ftl_connect->error;
	}
	
	// Close Connection
	$ftl_connect->close();
?>
MySQL - PDO(PHP Data Objects)
<?php

	try {
		$ftl_connect = new PDO("mysql:host=localhost;dbname=ftl_db", "root", "");
		// set the PDO error mode to exception
		$ftl_connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$sql = "CREATE DATABASE ftl_db";
		// use exec() because no results are returned
		$ftl_connect->exec($sql);
		echo "Database created successfully<br>";
		}
	catch(PDOException $e)
		{
		echo $sql . "<br>" . $e->getMessage();
		}
	
	$conn = null;

?>

The PDO is that it has exception class to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block. In the catch block above we echo the SQL statement and the generated error message.

We see you’re using an ad blocker.

Our website is made possible by displaying ads to our visitors.

Please help us continue to provide you with free. So please disabling your ad blocker.