WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Create a MySQL Database


A database comprises of at least one tables.

You will require exceptional CREATE benefits to make or to erase a MySQL database.


Create a MySQL Database Using MySQLi and PDO

The CREATE DATABASE explanation is utilized to make a database in MySQL.

The following models make a database named "myDB":

Example (MySQLi Object-oriented)

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

//Create connection
$conn = new mysqli($servername, $username, $password);
/Check connection
on the off chance that ($conn->connect_error) {
    die("Connection fizzled: " . $conn->connect_error);
}

//Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    reverberation "Database made successfully";
} else {
    reverberation "Error making database: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)

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

//Create connection
$conn = mysqli_connect($servername, $username, $password);
/Check connection
on the off chance that (!$conn) {
    die("Connection fizzled: " . mysqli_connect_error());
}

//Create database
$sql = "CREATE DATABASE myDB";
on the off chance that (mysqli_query($conn, $sql)) {
    reverberation "Database made successfully";
} else {
    reverberation "Error making database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Note: The accompanying PDO model make a database named "myDBPDO":

Example (PDO)

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

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    /set the PDO mistake mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "CREATE DATABASE myDBPDO";
   /use executive() in light of the fact that no results are returned
    $conn->exec($sql);
    reverberation "Database made successfully<br>";
    }
catch(PDOException $e)
    {
    reverberation $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

Tip: An extraordinary advantage of PDO is that it has special case class to deal with any issues that may happen in our database questions. On the off chance that an exemption is tossed inside the try{ } square, the content quits executing and streams straightforwardly to the first catch(){ } square. In the catch obstruct above we reverberation the SQL articulation and the created blunder message.