PHP – MySQL : Create Database

 

[root@mysqlDB]# mysqladmin -u root -p create eduguru
Enter password:******

This will create a MySQL database eduguru. This is a simple example to create database called eduguru.

Example:

<?php
$dbhost = 'localhost:3036';  //If mysql server is on same server
$dbuser = 'root';   //mysql user who has the permission to create database
$dbpass = 'rootpassword';  //mysql user's password
$conn = mysql_connect($dbhost, $dbuser, $dbpass);  //Connect to mysql database
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE eduguru';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not create database: ' . mysql_error());
}
echo "Database eduguru created successfully\n";
mysql_close($conn);
?>

 

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;

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

// Create database
$sql = “CREATE DATABASE eduguru”;
if ($conn->query($sql) === TRUE) {
echo “Database created successfully”;
} else {
echo “Error creating 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
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}

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

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;

try {
$conn = new PDO(“mysql:host=$servername;dbname=eduguru”, $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = “CREATE DATABASE eduguruPDO”;
// 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;
?>

Satya Prakash

VOIP Expert: More than 8 years of experience in Asterisk Development and Call Center operation Management. Unique Combination of Skill Set as IT, Analytics and operation management.

Leave a Reply