07- MySQL Create Database

0
68

MySQL Create Database

In order to create a MySQL database, you must have the privileges to Create or Delete Database. But for this tutorial, let’s assume that you have access to your server in PHPMyAdmin.

Creating MySQL Database using MySQLi and PDO

Basically, the statement used to create database is “CREATE DATABASE”. In our case, we will be using ‘mysqltutorial’ as our database name.

 

Example MySQLi (Object-Oriented):

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5.  
  6. // Create connection
  7. $conn = new mysqli($server, $username, $password);
  8. // Check connection
  9. if ($conn->connect_error) {
  10. die("Connection failed: " . $conn->connect_error);
  11. }
  12.  
  13. // Create database
  14. $sql = "CREATE DATABASE mysqltutorial";
  15. if ($conn->query($sql) === TRUE) {
  16. echo "Database created successfully";
  17. } else {
  18. echo "Error creating database: " . $conn->error;
  19. }
  20.  
  21. $conn->close();
  22. ?>

Example of MySQLi (Procedural):

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5.  
  6. // Create connection
  7. $conn = mysqli_connect($server, $username, $password);
  8. // Check connection
  9. if (!$conn) {
  10. die("Connection failed: " . mysqli_connect_error());
  11. }
  12.  
  13. // Create database
  14. $sql = "CREATE DATABASE mysqltutorial";
  15. if (mysqli_query($conn, $sql)) {
  16. echo "Database created successfully";
  17. } else {
  18. echo "Error creating database: " . mysqli_error($conn);
  19. }
  20.  
  21. mysqli_close($conn);
  22. ?>

Example of PDO:

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5.  
  6. try {
  7. $conn = new PDO("mysql:host=$server;dbname=mysqltutorial", $username, $password);
  8. // set the PDO error mode to exception
  9. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  10. $sql = "CREATE DATABASE mysqltutorial";
  11. // since there's no result, we use exec()
  12. $conn->exec($sql);
  13. echo "Database created successfully<br>";
  14. }
  15. catch(PDOException $e)
  16. {
  17. echo $sql . "
  18. " . $e->getMessage();
  19. }
  20.  
  21. $conn = null;
  22. ?>

 

Our Previous Topic called:  06- MySQL Connect

 

 

Facebook Comments
(Visited 47 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here