Daniel Miller Daniel Miller - 2 months ago 10x
PHP Question

Best practices when using PHP with Firebird or Interbase

The documentation for php-interbase is good - but not complete. In particular, there's no complete examples for working with Firebird. So how would you do it?


Basic guidelines.

  1. Choosing between ibase_connect() vs ibase_pconnect() - the less time connections are active the less possible conflicts and the easier maintenance & backups can be performed. Unless connecting to the database is "expensive" in terms of processing time (you're performing large amounts of real-time reads/writes) use ibase_connect() as needed.
  2. Always use explicit transactions. Always. It's simple - assume every call to ibase_prepare() or ibase_query() requires a transaction handle - never a "raw" connection handle.
  3. Always follow a transaction with either a ibase_commit() or a ibase_rollback() as appropriate.

Basic template for a read operation:

// These would normally come from an include file...
$db_path = '/var/lib/firebird/2.5/data/MyDatabase.fdb';
$db_user = 'SYSDBA';
$db_pass = 'masterkey';

// use php error handling
try {
    $dbh = ibase_connect( $db_path, $db_user, $db_pass );
    // Failure to connect 
    if ( !$dbh ) {
        throw new Exception( 'Failed to connect to database because: ' . ibase_errmsg(), ibase_errcode() );

    if ( !$th ) {
        throw new Exception( 'Unable to create new transaction because: ' . ibase_errmsg(), ibase_errcode() );

    $qs = 'select FIELD1, FIELD2, from SOMETABLE order by FIELD1';
    $qh = ibase_query( $th, $qs );

    if ( !$qh ) {
        throw new Exception( 'Unable to process query because: ' . ibase_errmsg(), ibase_errcode() );

    $rows = array();
    while ( $row = ibase_fetch_object( $qh ) ) {
        $rows[] = $row->NODE;

    // $rows[] now holds results. If there were any.

    // Even though nothing was changed the transaction must be
    // closed. Commit vs Rollback - question of style, but Commit
    // is encouraged. And there shouldn't <gasp>used the S word</gasp>
    // be an error for a read-only commit...

    if ( !ibase_commit( $th ) ) {
        throw new Exception( 'Unable to commit transaction because: ' . ibase_errmsg(), ibase_errcode() );

    // Good form would dictate error traps for these next two...
    // ...but these are the least likely to break...
    // and my fingers are getting tired.
    // Release PHP memory for the result set, and formally
    // close the database connection.
    ibase_free_result( $qh );
    ibase_close( $dbh );
} catch ( Exception $e ) {
    echo "Caught exception: $e\n";

// do whatever you need to do with rows[] here...