MySQL Create DB

Creating a database in MySQL using PHP involves establishing a connection and executing the appropriate SQL query. Below is a step-by-step guide:


Create a Database

Example - MySQLi (Procedural)
<?php
$servername = "localhost";
$username = "root"; // Change if needed
$password = ""; // Change if you have a password
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create 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);
?>

Example - MySQLi Object-oriented
<?php
$servername = "localhost";
$username = "root";
$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 mydatabase";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// Close connection
$conn->close();
?>

Note

The CREATE DATABASE SQL command is used to create the new database.

You can also create a database using the PDO extension:

Example - PDO
<?php
$servername = "localhost";
$username = "root";
$password = "";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create database
$sql = "CREATE DATABASE mydatabase";
$conn->exec($sql);
echo "Database created successfully";
} catch (PDOException $e) {
echo "Error creating database: " . $e->getMessage();
}

// Close connection
$conn = null;
?>


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.