How to Create MySQL Database?

How to Create MySQL Database?

We have to use “CREATE DATABASE” statement to create MySQL database.
Syntax:CREATE DATABASE database_name;

MySQL

      <?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE myDB';
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database myDB created successfullyn";
mysql_close($conn);
?>


MySQLi Object-oriented

 <?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$con = new mysqli($servername, $username, $password);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($con->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $con->error;
}

$con->close();
?>


MySQLi Procedural

 <?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?


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);
$sql = "CREATE DATABASE myDB";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Here, myDB is our database name. We can name it, whatever we want.

Post a Comment