HOME  |  WEB DESIGN  |  COMPUTING  |  GRAPHICS/PHOTOS  |  MUSIC
Web Sites Web Design Web Technology Panoramic Earth School Web Sites Summer Web Sites DLib PHP Library DLib PHP Library API database.php datetime.php dbautofuncs.php dbclasses.php dbdefines.php dbrecord.php dbscreens.php dbsync.php dbsync1.php dbsync2.php dlibinfo.php ecommerce.php formfields.php ftp.php functions.php graphical.php html.php htmldefines.php htmlpage.php lib.php numerical.php pdfgenlib.php protx.php session.php system.php tables.php

database.php

DLib PHP Library API

General database functions

This file contains all the general purpose generic functions for handling databases such as creating, opening and closing databases, general SQL functions, table update functions and other miscellaneous functions. See dbclasses.php and dbrecord.php for the OO database classes and dbautofuncs.php for useful functions that are generated on-the-fly when record classes are created. Also, see the various db_xxxx.php files for database-type specific implementations (e.g. db_mysql.php or db_access.php).

The following code shows how a database connection is created, switched to and then opened. Records from a Stock Item table are then read (see dbclasses.php for how to define record layouts).

EXAMPLE
  $con1 = newDbConnection ("mysql", "localhost", "dblocal", "dbuser",
    "abcd123", "root", "rootpswd");

  switchDatabase ($con1);

  if (dbConnect ())
  {
    list ($ok, $stkList) = readStockItems ("cost < 0.50");

    foreach ($stkList as $stk)
      print "$stk->code - $stk->description - $stk->price\n";

    dbClose ();
  }

Class/Function/Method List

File Version: 5.4.4 - 5 Jun, 2008


Up arrowstring addSQL ($where, $sql, [$doOR])

Adds another bit of SQL statement to make up a WHERE statement for SQL. Similar to addWhere except that it does not assumes the presence of a global $where variable.

Result: Returns the new $where string.

Param Type Details
$where string The WHERE string that should have the SQL added.
$sql string The new SQL to be added to the $where variable.
[$doOR] boolean Adds OR instead of AND if true.

Up arrowvoid addTable ($tableName, $className, [$autoFuncs], [$modName])

Add a table definition to the current settings. Creates a global TableDef variable called $tdXXX where XXX is $className. Optionally creates the default standard database functions associated with that class (see dbautofuncs.php). See dbclasses.php for the TableDef class.

Param Type Details
$tableName string The database table name used for this table.
$className string The class name used to represent a database record for the specified table.
[$autoFuncs] boolean Default = false. If true then create the database auto-functions (see dbautofuncs.php). A copy of this flag is stored in the TableDef.
[$modName] boolean Default = true. Passed straight to dbAutoFuncs (see dbautofuncs.php). A copy of this flag is stored in the TableDef.
EXAMPLE
Add a table called stockitems to the current table definitions and associate it with the StockItem record type. Allow the system to create the Auto Functions (see dbautofuncs.php) so that we can call functions such as readStockItems and countStockItems without actually needing to create them manually.
  addTable ("stockitems", "StockItem", true);

Up arrowvoid addWhere ($sql, [$doOR], [$clr])

Adds another bit of SQL statement to make up a WHERE statement for SQL - assumes the presence of a global $where variable being used by the calling code.

Param Type Details
$sql string The new SQL to be added to the $where variable.
[$doOR] boolean Adds OR instead of AND if true.
[$clr] boolean Clear the global $where variable before adding the new SQL.
EXAMPLE
We have a database table containing contact names and addresses and $name and $town have been passed in from a search form. This code will then populate the WHERE statement ready to be sent to an SQL read function (in this case readContacts).
  $where = "";

  if (!empty ($name))
    addWhere ("name LIKE '%$name%'");

  if (!empty ($town))
    addWhere ("town LIKE '%$town%'");

  list ($ok, $recList) = readContacts ($where, "name");

Up arrowvoid createTables ()

Create all tables using data in $_db->tables (from classes that extend (Ex)DbRecord). Note that only table allowed in the currently enabled database will be created.


Up arrowboolean dbClose ()

Close the currently selected database. To close multiple databases then use switchDatabase to select a db and then close it using this function.

Result: True if database successfully closed.


Up arrowboolean dbConnect ()

Connect to the specified database optionally creating the database if allowed. If we don't find any records in the systemval table then attempt to do a create on all the tables.

Result: True if the connect succeeded.

EXAMPLE
Set up a database connection, switch to it and then try to connect.
  $con1 = newDbConnection ("mysql", "localhost", "dblocal", "dbuser", "abcd123");

  switchDatabase ($con1);

  if (dbConnect ())
  {
    // Connection succeeded!

    // Do some database access here...
  }

Up arrowvoid dbMsg ($msg)

Database message handler. This accumulates database errors into one string for later display.

Param Type Details
$msg string Message to add to the database error messages string.

Up arrowvoid dbUpdate ()

Check to see if a database update is required. This is performed either once a day, once an hour or every time this function is called (depending upon the setting of $_db->dbChanges).


Up arrowboolean doSQL ($sql)

Execute an SQL statement. If it fails then it checks for record layout changes and, if found, attempts to update the table (except for SystemVal).

Result: Returns true if SQL succeeded.

Param Type Details
$sql string The SQL statement to be executed.
EXAMPLE
  if (doSQL ("UPDATE stockitems SET price = 10.23 WHERE ref = 'A2-DEX'"))
    print "Update succeeded";

Up arrow[mixed] fieldDetails ($table, $field)

Return the DbField info about the specified field in the specified table.

Result: Returns a two element array: 0 = a boolean success indicator; 1 = an (Ex)DbField class record containing the field details.

Param Type Details
$table string The table name.
$field string The field name.

Up arrowstring getDbTrace ([$addBR])

Return the current database trace as a string.

Result: String containing a formatted copy of the current DB trace.

Param Type Details
[$addBR] boolean Adds BR tags between lines (default is false).

Up arrowint newDbConnection ($dbType, $dbHost, $dbName, $dbUser, $dbPswd, [$dbMaster], [$dbMPswd], [$dbPrefix])

Set up a database connection's details. Any number of connections can be set up and then switched between using the switchDatabase function.

Result: Connection number.

Param Type Details
$dbType string The database type (mysql, odbc, odbclink, access, etc - there must be the equivalent db_xxxx.php plug-in for when database type xxxx is being used).
$dbHost string Server host name.
$dbName string Database name.
$dbUser string Database user name.
$dbPswd string Password.
[$dbMaster] string Database root access user name (allows database creation and dropping).
[$dbMPswd] string Database root access password.
[$dbPrefix] string Database table prefix.
EXAMPLE
Set up connection 1 to a local MySQL database and control over database creation (by sending the root user name and password), and connection 2 to a remote MS Access database where we also do not have control over database creation.
  $con1 = newDbConnection ("mysql", "localhost", "dblocal", "dbuser",
    "abcd123", "root", "rootpswd");

  $con2 = newDbConnection ("access", "www.banana.org", "dbxyz",
    "dbuser", "defg987");

Up arrowarray readFromMulti ($classNames, $joinFlds, [$where], [$order], [$limit], [$fields], [$groupby])

Read from multiple tables.

Result: Element 0 is either true or false denoting the success or otherwise of the call. Element 1 is an array of objects where each object itself an array of the specified class records.

Param Type Details
$classNames string A comma separated list of the class types that have to be interrogated. Each class type gets renamed as tn where n is an incrementing value starting at 0. For example, if the class types list is "Company,Addr" (which could represent some classes containing compnay info along with multiple addresses) then Company will be t0 and Addr becomes t1. These conventions must be used in the WHERE and ORDER BY clauses below - e.g. to order by the Company name use "t0.name".
$joinFlds [string] An array of link fields such as "t0.ref=t2.xref". Older versions use a comma separated list of the common fields that link all the specified tables together (DEPRECATED). If a field to be matched has different names in different tables then use: name1;name2[;name3...] where there must be one entry for each value in the classNames parameter.
[$where] string SQL WHERE clause.
[$order] string SQL ORDER BY clause.
[$limit] string Optional LIMIT value(s) (currently MySQL style only).
[$fields] mixed Either:
  • An array of the fields required (if omitted then all fields are returned for all tables). Each array is a CSV of the field names. Element 0 is the CSV of fields required from the first table, element 1 for the second etc. A field name can be preceded by "DISTINCT ".
  • An "*" which forces the return of a count of the records instead.
[$groupby] string Any GROUP BY value required.
EXAMPLE
Read the businesses and associated addresses and print them out.
  list ($ok, $recList) = readFromMulti ("Business,Address", "ref",
    "t1.town LIKE '%Hampstead%', "t0.name");

  foreach ($recList as $rec)
  {
    list ($business, $address) = $rec;
    print $business->name . "\n" . $address->addr1 . "\n" .
      $address->town;
  }

Up arrowvoid removeDbMsg ()

Remove the last entry from dbMsg. Used where an error occurs but is then handled properly by the calling code.


Up arrowvoid switchDatabase ($con, [$connect])

Change which database we are currently accessing.

Param Type Details
$con int A database connection number as returned by the newDBConnection function.
[$connect] boolean If true then attempt to connect to the database as well.
EXAMPLE
Assuming that $con1 and $con2 have been set up as connections to two separate databases and we have also performed a successful dbConnect call to both of them then we can switch between them. This example reads some records from one database and then saves them to a second before switching back to the original database. Note that we check for the record already existing in the second database and, if it is NOT found, then we set newRec - internally, this tells the system that this is a new record which creates the correct SQL to do an INSERT instead of an UPDATE statement.
  switchDatabase ($con1);
  list ($ok, $recList) = readStockItems ("cost < 0.50");

  if ($ok)
  {
    switchDatabase ($con2);

    foreach ($recList as $rec)
    {
      $rec2 = new StockItem ($rec->ref);

      if (!$rec2->ok)
        $rec->newRec = true;

      $rec->save ();
    }

    switchDatabase ($con1);
  }

Up arrow[mixed] tableDetails ($name, [$isClass])

Get table entry from the table or class name name.

Result: Returns an array of 3 items: 0 = boolean success indicator; 1 = the associated (Ex)TableDef class; 2 = a blank instance of the associated record class.

Param Type Details
$name string The table or class name from which to return information.
[$isClass] boolean If true then search via the class name instead.

Up arrowboolean transBegin ()

Begin a transaction. Note that these Transaction functions can only be used on tables that can handle transactions (e.g. InnoDB, BDB etc for MySQL).

Result: Success value.


Up arrowboolean transCommit ()

Commit (end) a transaction.

Result: Success value.


Up arrowboolean transEnd ()

End (commit) a transaction - alternate name.

Result: Success value.


Up arrowboolean transRollback ()

Roll back a transaction.

Result: Success value.


Up arrowvoid updateTable ($table)

Update a table definition. This compares the stored record layout with the DbField entries for that record and, if differences are detected, then it attempts to automatically update the database table to bring them into sync.

Param Type Details
$table string The name of the table to be updated.

Up arrowvoid updateTables ()

Checks to see if any tables need updating (calls updateTable for all tables defined).