Create a MySQL Database Using PHP

In this article i will show you how to create MySQL Database Using PHP.

 

What is a database?

A database is a collection of related data that helps to successfully retrieve, add and delete data from a database and organize data in the form of tables, views, reports etc. intelligence, and management staff etc. which assists in the successful retrieval, installation and deletion of data.

We know that in MySQL to build a database we need to make a query. Read this article carefully

easy & simple methods to create a MySQL database using PHP:

  • Establish a connection to the MySQL server from your PHP script as described in this article.
  • If the connection is successful, type a SQL query to create a website and save it to a string variable.

 

Create a MySQL Database using MySQLi and PDO

MySQLi Object-Oriented

MySQLi Object-oriented

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

// Create connection
$conn = new mysqli($servername, $username, $password);

// Checking Connection

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
  }

// Create database


$sql = "CREATE DATABASE myDataBase";
if ($conn->query($sql) === TRUE) {
  echo "Database Created Successfully";
  } else {
    echo "Error To Creating Database: " . $conn->error;
    }

// closing connection
$conn->close()

?>

Note:When you creating a new database, you must specify this arguments to the mysqli object (servername, username and password).

 

MySQLi Procedural

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

// Creating Connection

$conn = mysqli_connect($servername,$username, $password);

// Checking connection

if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
  }
  
// Creating database

$sql = "CREATE DATABASE myDataBase";
if (mysqli_query($conn, $sql)) {
  echo "Database Created Successfully";
  } else {
    echo "Error creating database: " . mysqli_error($conn);
    }

// Close Connection
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 myDataBase";
          // 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;
?>

 

Leave a Comment

Your email address will not be published.