Using databases
Previous  Next

«A database is a collection of logically related data designed to meet the information needs of one or more users.» from Wikipedia

There are many unfortunate cases in your life in which you will end up using a database; for example storing customers' data, their orders, their broken toys to repair etc.

With the power of a relational database, you can add exponential complexity to your problem and possibly solve it in a few sleepless nights, but nothing will compare to the claim "I am using a database" that you will be able to do.

Database existence
Let's see how to find out which databases currently exist on the server:

<?php
            include 'gladius/gladius.php';

            $G = new Gladius();

            $rs = $G->Query('SHOW DATABASES');

            // print the databases
            print_r($rs->GetArray());
?>

You will probably obtain this output:

Array ( )

So there are no existing databases; now let's create a nice new database. You will get a different result if there are folders in the current script's folder.

Database creation
Note that unless you have specified a different Gladius DB root directory, databases will be created in and read from the current script directory and you should have the proper rights for directory/files creation.

<?php
            include 'gladius/gladius.php';

            $G = new Gladius();

            if (!$G->Query('CREATE DATABASE myshop'))
                        die($G->errstr);

            $rs = $G->Query('SHOW DATABASES');           

            // print the databases
            print_r($rs->GetArray());
?>

And the output should be:

Array
(
    [0] => Array
        (
            [database] => myshop
            [version] => 0.7
        )

)

If you have received the error Cannot create database "myshop" you should check your write permissions on the script's directory.

Database selection
Now let's take control of this new empty database; in technical terms "taking control of a database" is selecting a database. You can perform this operation in two different ways, via SQL and via the API. We will explore the latter option in this tutorial.

<?php
            include 'gladius/gladius.php';

            $G = new Gladius();

            // call the database selection method
            $G->SelectDB('myshop');

            // show the eventual error message
            echo $G->errstr;
?>

Selecting a database has the purpose of actually using it. Proceed to the next section Using tables to read more.