TextDB Tutorial

From MyUPBWiki

Jump to: navigation, search

Examples by Tim Hoeppner and websmart

Contents

General Information needed

tdb.class is a PHP class. A class is a collection of different functions.
It is not a script you can right away use by http://yoursite.com/tdb.class.php
but in your PHP pages, you 'include' the class and then call required 'functions' from the class to carry out different jobs.

In your PHP pages, you 'include' the class like this :

<?PHP 
include_once("tdb.class.php"); 

this will give effect like entire code from that appears on your PHP page, all functions from that active and ready to be used by your PHP page. Next, you start using required functions to create database, tables, populate records and displaying, modifying and deleting your records

In the beginning, you may have to do some wrestling with file and directory permissions depending on your host settings. My host, reasons known only to them, produces error when PHP scripts try to CHMOD files and gives 'CHMOD() permission denied' error. So scripts setting file permission themselves stop there when trying to give file permissions automatically. Then I have to comment out lines which try to CHMOD, see what those lines were trying to do, and then through FTP, I set required 'read,write,execute' permissions for files in question.

Class was not being able to 'create' database for me, so I had to create a blank file named 'medbase.tdb', upload it to server, then through FTP i gave that file 777 (full read,write,execute) permissions, after that the class became able to create necessary tables for me.

After you are through any 'teething troubles', create example tables first, and when you become able to carry out routine database jobs on those tables like add new records, display records on webpages, modifying and deleting records from files, then you can start to work on real data, as you sort out normal problems before working with hundreds or thousands of real data and then find out about errors. Always keep on working on test data until you are able to perform record and field level operations satisfactorily on your tables.

Now let us understand tdb functions for your database.

First, you need to create a database. A database is a platform on which you place one or more tables. Whenever you 'Open' a database (or 'connect' to a database), tables placed under that database becomes available to you for processing.

// Including the class <br />
include tdb.class.php; 

// Initializing the class, $directory being the directory where the database is located <br />
// and $filename being the filename of the text database. <br />
// NOTE: $db can be any variable name <br />
$db = new tdb($directory, $filename); <br />

// Cleaning up, $db being the var you used to initialize the class <br />
// NOTE: it would be a good idea to do this at the end of your scripts. <br />
$db->cleanUp();

// NOTES: $db->function() accesses a function from the class, function being the <br />
// name of the function and $db being the var used to initailize the class 

// Everything in textdb is case sensitive meaning "a" is different from "A" 

Creating a new database

$db = new tdb("", ""); <br /><br />
$db->createDatabase($dir, $filename); <br />
like this : $db->createDatabase("./mydatadir","texas.tdb"); 

in above example it is assumed 'mydatadir' is directory UNDER where your tdb.class.php is sitting. If path to 'mydatadir' directory is /home/user/public/mydatadir , your class and PHP file which is calling the class are sitting in /home/user/public directory. When you write directory name like "./mydatadir" you are telling the class that directory in which I want to put my database and tables is named 'mydatadir' and it is sub-directory right Under THIS current directory. You are free to name 'mydatadir' any name you want.

Creating a new table in a existing database

After your database 'texas.tdb' is created for you (if not, create blank file named 'texas.tdb' and CHMOD it 777 so that class can read/write in that database whenever required. Now you can add a table in the database :

$db->createTable($fp,array(array(fieldname, type, size)));

INTRO: Creating new tables can be a little complicated at first but once you get the hang of it its pretty straight forward

SITUATION: For this example I want to create a table to manage all of my client profiles, I think a suitable name for this would be "clientInfo" I am going to need 3 things from my clients: their full name (fullName), phone number (phoneNum), and there interests (interests). Since the full name is generally about 15 - 25 characters we will set the field length to 25 and field type to string. Since we will deal with local phone numbers only we will need 7 digits so the length will be 7 and the field type will be a number. Interests might be small but might be big, this would be appropriete to set this field to a memo type with no size set. I think it would also be a good idea to give all the clients a unique identification number so what we can reference to them using a simple number. We will call this field "clientId" and have the field type id with no length.

THE CODE assuming you have the class initialized already and var used was $db

$db->createTable("clientInfo", array(array("fullName", "string", 25), array("phoneNum", "number", 7), array("interests", "memo"), array("clientId", "id")));

Data Types

"string" type fields hold all characters.

"number" type fields will let you enter numeric values only. decimal point are allowed, no other characters are allowed

"memo" type fields are special 'string' type fields with no pre-determined length. Suitable for data like remarks, product descriptions etc. For one product, your description may be just two words, for other product you may want to write few paragraphs about that.

"id" is a special type. It generates auto-increment numbers to identify records. If you add a new record and write only "fullName" field and "phoneNumber" fields, and previous record's "id" was 8, in new record, "id" will be written as 9 automatically. This way, you can point to particular record to be modified or removed when other details are same. You can have two "john smith" in a membership table, and one john decides to cancel the membership, you can tell the class to remove member who has "id" number so and so.

How to and why we create filepointers

First off i will just let you know what a filepointer is. It is a pointer (reference) to a existing table

CREATING A FILEPOINTER: so we have a table called clientInfo and we want to create a reference to it, the reference will be called "info"

$db->setFp("info", "clientInfo");

REASONING: take this situation, lets say your selling stuff and each of your clients buys things and for each thing he buys he gets a bill made. To store these bills in the client database we could name the tables bills*clientID* replacing *clientId* with the actual identification number that we made in the clientInfo table. Your probably wondering still whats the point well check this out. You make a dynamic web page allowing clients to view their bills the page requires a query string var "clientId" used to retrieve that clients bills. so now you can simply have just one line that uses that querystring

$db->setFp("bills", "bills".$_GET["clientId"]);

Adding Records to an existing table

INTRO: A record is some data with meaning with the ability to add, edit and delete them with no effect to any of the other records

SITUATION: I would like to add a new client named John Smith (who would have guessed) his phone number is 5551234 and his interests are "I like long walks on the beach and hanging with my girlfriend suzy"

THE CODE assuming you have already made a filepointer for the clientInfo table which is "info"

$db->add("info", array("fullname" => "John Smith", "phoneNum" => "5551234","interests" => "I like long walks on the beach and hanging with my girlfriend suzy"));

Note that after we created a pointer "info" to the table "clientInfo", when we added a new record, we told class to add record to "info", not "clientInfo".

Also note, that we did not worry about writing data about "id" field "clientId". "id" field being auto-increment, class will take care to insert proper value for that. This way you can keep on adding records without risking entering duplicate 'clientId' value and keep it a unique number to identify your record.

Deleting Records from an existing table

INTRO: I have to situations when deleting records, one when you are just deleting one record and one where you delete many records. I will show you how to do both.

SITUATION 1: Peter Yohan is moving to another country and will no longer be needing an account with your business. So we want to delete his account from our records. Peters clientId is 24.

THE CODE assuming you have a filepointer setup for clientInfo called info $db->delete("info", 24);

SITUATION 2: Several of your clients arn't paying there bills so you deside to cut them off from buying anything more so you delete there accounts. The clientId's are 12, 39, 41, and 66.

THE CODE assuming you have a filepointer setup for clientInfo called info

$db->delete("info", 12, false); <br />
$db->delete("info", 39, false); <br />
$db->delete("info", 41, false); <br />
$db->delete("info", 66); 

NOTE: you'll notice on all but the last that there is an extra argument "false" all you need to make sure is that you don't put false on the last one. By doing this your scripts will be more efficient (at least the ones that delete multiple records anyways)

Editing Records from an existing table

INTRO: Not only can you add and delete but you can edit existing records in a table. To do this we use the edit function as you will see below.

SITUATION: John Smith has moved and his phone number changed (5559632). John also got married to Suzy and for some reason changed his last name to hers (Ryme). Johns clientId is 1.

THE CODE assuming you have a filepointer setup for clientInfo called info

$db->edit("info", 1, array("fullName" => "John Ryme", "phoneNum" => "5559632"));

Using listRec() on a existing table

INTRO: Well your probably thinking what does it do in the first place? To put it simply it returns a range (specified by you) of records. In textdb each record has a file Id and a record Id. The record id never changes but anytime you delete something from the table some file Id's may change all depending where that record you deleted was located. This function is really useful for paging results (1-10, 11-20) because it doesn't care about record id's.

SITUATION: The administrator (you) is viewing all your clients and you have made it so that it only shows 10 results at a time. Lets say you're on the 3rd page so you want 21-30.

THE CODE assuming you have a filepointer setup for clientInfo called info

$result = $db->listRec("info", 21, 10); <br />
//displaying the result  <br />
for($i=0;$i<count($result);$i++) {<br /> 
echo "<p> <br />
Full Name: ".$result[$i]["fullName"]." <br />
Phone #: ".$result[$i]["phoneNum"]." <br />
Interests: ".$result[$i]["interests"]." <br />
</p>"; <br />
} 

NOTE: the second argument is where to start and the 3rd is how many records you want and since we wanted 21-30, we started at 21 and got 10 records.

NOTE: the 3rd argument is optional, if nothing is put there all records after start will be returned.

Using query() on a existing table

INTRO: query is a different way of display results. What it allows you to do is to for example only display clients with a full name of "John Smith"

SITUATION: We want to display all the people that have a full name of John Smith and phone number starts with 822.

THE CODE assuming you have a filepointer setup for clientInfo called info

$result = $db->query("info", "fullName='John Smith'&&phone?'822'"); <br />
//displaying the result <br />
for($i=0;$i<count($result);$i++) { <br />
echo "<p> <br />
Full Name: ".$result[$i]["fullName"]." <br />
Phone #: ".$result[$i]["phoneNum"]." <br />
Interests: ".$result[$i]["interests"]." <br />
</p>"; <br />
} 

Now an explanation for the query function

here is the basic layout of the function:

$db->query(filepointer, query, start, howmany);

filepointer is the file pointer you make with setFp() query is the querystring you use to determine which records to select start is the result to start on, if there is 23 results for a query and you can tell it to start on the 11th one. This is nice for paging results. howmany is howmany results you want to return so if you want the second page of result if you show 10 per page you would use 11 as start and 10 as howmany.

HOW-TO make a query string

the querystring has a few parts:

field='value'

field is the field you want to test
= is the option you want (i will get to those)
value surrounded in single quotes is the value you want to test with

options

= will test for exact value
? will test if the value exists somewhere in the value
< this tests if the value in the table is less than the test value
> this tests if the value in the table is greater than the test value

Using get() on a existing table

INTRO: get() can "get" you a single record fast and very simple as long as you know the record id

SITUATION: I want to view Jane Smith's information, her clientId is 7.

THE CODE assuming you have a filepointer setup for clientInfo called info

$result = $db->get("info", 7); <br />
//displaying the result <br />
echo "<p> <br />
Full Name: ".$result[0]["fullName"]." <br />
Phone #: ".$result[0]["phoneNum"]." <br />
Interests: ".$result[0]["interests"]." <br />
</p>"; 

Sorting a table

INTRO: Having results in order is always nice and the function i'm going to show you here is just what you need

SITUATION: You're having trouble finding clients in the big list you have already and it would be alot easier if it was all sorted by there full name. So to fix the problem we are going to rebuild the table with sorted data. We want the data a-z so ASC (z-a is DESC)

THE CODE assuming you have a filepointer setup for clientInfo called info

$db->sortAndRebuild("info", "fullName", "ASC");

NOTE: it would be smart to sort the data after a add or edit has taken place.

Extra Functions

addField($fp, array(fieldname, type, size)) - creates a new field in the table
editField($fp, $field, array(newname, newtype, newsize)) - edits an existing field
removeField($fp, $field) - removes a field from a table
getNumberOfRecords($fp) - returns the number of records in the table
getTableList() - returns a list of avaiable tables in the database
getFieldList($fp) - returns a list of all the fields in a table
version() - returns the version

Personal tools