19 Jan 10 Create a New MySQL Database with PHP



In our last article we discussed creating a MySQL database using phpMyAdmin, but what if we want to do it using PHP alone? We can do that. This tutorial will show how.

We will use four PHP functions:

  1. mysql_connect. This opens a connection to the MySQL server.
  2. mysql_error. If there is a problem, this gives us the error message.
  3. mysq_query. This sends (queries) MySQL information to the server.
  4. mysql_close. This closes your connection to the server.

In this example, we will create a database called “movies”. We will assume the MySQL server is on the localhost which it is if you are running WampServer 2 as recommended in our tutorials.

The following code will create our database. Please read the comments to understand what is happening.

<?php
// First we will connect to our server.
// Indicate the server address, username, and password.
// If you have followed our tutorials since the beginning, your username is root.
 
$link = mysql_connect("localhost","root","YOUR-PASSWORD-HERE");
 
// Now we will check to see if our $link variable shows we connected.
if (!$link) // If it did not connect...
  {
  die('Sorry, I encountered this error: ' . mysql_error());
  // The die function ends the script and uses the mysql_error to show us why we could not connect.
  }
 
// If we've made it this far, then our connection was successful.
// So now we will create our database using the SQL "create database" command.
 
// Using the $link connection, send our request to the server to create our movies database.
if (mysql_query("CREATE DATABASE movies",$link))
  {
  // If successful, tell us it worked.
  echo "Database has been created.";
  }
else // But if it doesn't work, tell us why...
  {
  echo "Could not create database: " . mysql_error();
  }
 
// Now that we are finished with the connection, we will close it.
mysql_close($link);
?>

And there it is. If successful, you will now have an empty database called “movies”. In our next tutorial, we will learn how to create tables in the database.

Tags: , , , ,

Reader's Comments

  1. |

    Hi, your articles are very well-written and easy to follow. When can we expect to see more?

    Reply to this comment
    • |

      Thanks for your kind comment. :)

      Unfortunately, I don’t expect to be writing more tutorials in the near future. I have other (higher priority) projects that are keeping me busy.

      Reply to this comment

Leave a Comment