ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

07-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 . "<br>" . $e->getMessage();
  18. }
  19.  
  20. $conn = null;
  21. ?>

 

 

 

 

 

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!