Team LiB
Previous Section Next Section

Creating a New Database

The complex elements of the previous scripts are nowhere to be found in this next script. The goal of this script is to create a new database on the MySQL server.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create a variable to hold the query to issue, which will create the new database:

    $sql = "CREATE database testDB2";
    
  3. Add the connection information just as you have been doing:

    $connection = @mysql_connect("localhost", "spike", "9sj7En4")
         or die(mysql_error());
    
  4. Issue the query, using the mysql_query() function. Include the @ to suppress warnings, as well as the die() function to cause the script to end and a message to be displayed if the query fails:

    $result = @mysqlquery($sql, $connection) or die(mysql_error());
    
    
  5. Test the value of $result. If it's true, the query was successful, and a variable is created to hold a message:

    if ($result) {
         $msg = "<P>Database has been created!</P>";
    }
    
  6. Close your PHP block, and then add HTML:

    ?>
    <HTML>
    <HEAD>
    <TITLE>Create a MySQL Database</TITLE>
    </HEAD>
    <BODY>
    
  7. Print the message string:

    <? echo "$msg"; ?>
    
  8. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  9. Save the file with the name db_createdb.php, and place this file in the document root of your web server.

  10. Open your web browser and type http://127.0.0.1/db_createdb.php.

If the database creation was successful, you'll see the message shown in the following figure.

Click To expand

Verify that the new database is present by opening your web browser to http://127.0.01/db_listdb.php.

You should see your new database in the list.

Click To expand

In the next section, you drop (delete) the database you just created.


Team LiB
Previous Section Next Section