Tutorial 1: Use the txt-db-api

The txt-db-api is simple to use. A php-site which uses the api does the following steps:

1. Include the Txt-Db-Api

<?php
include ("../php-api/txt-db-api.php");
?>

It's important that you specify the correct path to the txt-db-api.php file. That's the only
file you need to inlcude in order to work with the txt-db-api library.

2. Create a Database Object

If you have done the installation correctly and the corresponding folder for the database were created
(via FTP or with a CREATE DATABASE statement), you can now create a Database Object.
You must specify the name (i.e. a subfolder of $DB_DIR) of the Database in the constructor.
Database names are case-sensitive.

$db = new Database("myDatabase");


3. Execute SQL Statements

Once you have a Database Object, you can now execute as many SQL-Statemens on it as you like.
To execute a SQL-Statement use the executeQuery() function.

$rs=$db->executeQuery("SELECT name, prename, zip AS zipCode FROM people WHERE zip='1234' ORDER BY name; ");

The ";" at the end of the SQL-String is optional. The executeQuery() method returns a different value dependant on the SQL-Statement type. It can be either a boolean, a int or a ResultSet. (the return types are documented here)

 

4. Display the ResultSet (Only with SELECT Statements)

SELECT statements return a result set object, which contains the data of the query. There are different ways to query the data stored in a result set object.

Example #1: A while-loop method:

while($rs->next())
{ ... }

The next() method above traverses the result set to the next row. Note that before the next() method is called for the first time, the position of the result set is not at the beginning, it is one record before the beginning. Therefore, the first reference to next() will be at the first record!.

While in the while loop, you can now use any of the following 3 methods to obtain current row values:

  • getCurrentValues
  • getCurrentValueByName
  • getCurrentValueByNr

    Example:
    list($name,$prename,$zip)=$rs->getCurrentValues();
    	echo "$name $prename  has the zip code $zip";