繁体   English   中英

将PHP与Firebird或Interbase一起使用时的最佳实践

[英]Best practices when using PHP with Firebird or Interbase

php-interbase的文档很好-但不完整。 特别是,没有使用Firebird的完整示例。 那你会怎么做呢?

基本准则。

  1. 在ibase_connect()和ibase_pconnect()之间进行选择-连接活动的时间越短,冲突就越少,维护和备份也就越容易。 除非连接到数据库在处理时间方面“昂贵”(您要执行大量的实时读取/写入),否则请根据需要使用ibase_connect()。
  2. 始终使用显式事务。 总是。 这很简单-假设每次对ibase_prepare()或ibase_query()的调用都需要事务句柄-永远不要使用“原始”连接句柄。
  3. 请始终在适当的情况下使用ibase_commit()或ibase_rollback()跟随事务。

读操作的基本模板:

// 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() );
    }

    $th = ibase_trans( $dbh, IBASE_READ+IBASE_COMMITTED+IBASE_REC_NO_VERSION);
    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...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM