PHP code example of satwareag / php-firebird

1. Go to this page and download the library: Download satwareag/php-firebird library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

satwareag / php-firebird example snippets



// Connect to Firebird database
$db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');

if (!$db) {
    throw new Exception('Connection failed: ' . fbird_errmsg());
}

// Execute a query with parameters
$result = fbird_query($db, 'SELECT * FROM users WHERE active = ?', 1);

if (!$result) {
    throw new Exception('Query failed: ' . fbird_errmsg());
}

// Fetch data
$users = [];
while ($row = fbird_fetch_assoc($result)) {
    $users[] = $row;
}

// Clean up
fbird_free_result($result);
fbird_close($db);

print_r($users);


// Enable exception mode (PDO-style error handling)
fbird_set_exception_mode(FBIRD_EXCEPTION_MODE_THROW);

try {
    $db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');
    $result = fbird_query($db, 'SELECT * FROM invalid_table');
} catch (Firebird\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo "SQLSTATE: " . $e->getSqlState() . "\n";  // e.g., "42000"
    echo "Error code: " . $e->getCode() . "\n";
}

// Switch back to silent mode (traditional PHP warnings)
fbird_set_exception_mode(FBIRD_EXCEPTION_MODE_SILENT);

// Traditional error handling with warnings
$db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');
if (!$db) {
    echo "Connection failed: " . fbird_errmsg() . "\n";
}


// Early in your bootstrap (before any database operations)
fbird_set_exception_mode(FBIRD_EXCEPTION_MODE_THROW);


$db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');

// Start a transaction
$trans = fbird_trans($db);

try {
    fbird_query($trans, "INSERT INTO users (name) VALUES (?)", 'Alice');
    fbird_query($trans, "INSERT INTO logs (message) VALUES (?)", 'User Alice created');
    
    // Commit if all operations succeed
    fbird_commit($trans);
    echo "Transaction committed successfully\n";
} catch (Exception $e) {
    // Rollback on error
    fbird_rollback($trans);
    echo "Transaction rolled back: " . $e->getMessage() . "\n";
}

fbird_close($db);


$db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');

// Simple: Use flag-first API for common configurations
// Read-only transaction with SNAPSHOT isolation (CONCURRENCY)
$readTrans = fbird_trans(FBIRD_READ | FBIRD_CONCURRENCY, $db);

// Read-write with READ COMMITTED + record versioning + wait
$writeTrans = fbird_trans(FBIRD_WRITE | FBIRD_COMMITTED | FBIRD_REC_VERSION | FBIRD_WAIT, $db);

// Advanced: Use array options for full TPB control
$options = [
    'access_mode' => FBIRD_WRITE,
    'isolation' => FBIRD_COMMITTED,
    'lock_resolution' => FBIRD_WAIT,
    'lock_timeout' => 10,  // 10 second timeout
    'tables' => [
        'USERS' => FBIRD_LOCK_PROTECTED | FBIRD_LOCK_WRITE,
        'LOGS' => FBIRD_LOCK_SHARED | FBIRD_LOCK_READ
    ]
];
$trans = fbird_trans_start($db, $options);

// Query using the transaction
fbird_query($trans, "UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?", 123);

// Inspect transaction state
$info = fbird_trans_info($trans);
print_r($info);
// Output: ['id' => 12345, 'state' => 'ACTIVE', 'isolation' => 'READ_COMMITTED', ...]

fbird_commit($trans);
fbird_close($db);


$db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');

// Prepare a statement for repeated execution
$stmt = fbird_prepare($db, 'SELECT * FROM users WHERE id = ?');

for ($i = 1; $i <= 10; $i++) {
    $result = fbird_execute($stmt, $i);
    if ($row = fbird_fetch_assoc($result)) {
        echo "User $i: " . $row['NAME'] . "\n";
    }
    fbird_free_result($result);
}

fbird_free_query($stmt);
fbird_close($db);


$db = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');

// Create a BLOB
$blob = fbird_blob_create($db);
fbird_blob_add($blob, "This is the content of the BLOB field.");
$blob_id = fbird_blob_close($blob);

// Insert the BLOB
fbird_query($db, "INSERT INTO documents (content) VALUES (?)", $blob_id);

// Read a BLOB
$result = fbird_query($db, "SELECT content FROM documents WHERE id = 1");
$row = fbird_fetch_assoc($result);
$content = fbird_blob_info($db, $row['CONTENT']);

echo "BLOB length: " . $content['length'] . " bytes\n";

fbird_free_result($result);
fbird_close($db);


// Same parameters = same connection (by design)
$conn1 = fbird_connect('/path/to/db.fdb', 'SYSDBA', 'masterkey');
$conn2 = fbird_connect('/path/to/db.fdb', 'SYSDBA', 'masterkey');

// $conn1 and $conn2 reference the SAME connection resource
var_dump($conn1 === $conn2);  // bool(true)


// Approach 1: Use different parameters (charset, role, etc.)
$conn1 = fbird_connect($db, $user, $pass, 'UTF8');
$conn2 = fbird_connect($db, $user, $pass, 'ISO8859_1');  // Different charset = new connection

// Approach 2: Use different roles
$admin = fbird_connect($db, $user, $pass, null, null, null, 'ADMIN');
$reader = fbird_connect($db, $user, $pass, null, null, null, 'READER');

// Approach 3: Mix persistent and non-persistent
$conn1 = fbird_connect($db, $user, $pass);
$conn2 = fbird_pconnect($db, $user, $pass);  // Different pool


// Force a new connection even with identical parameters
$conn1 = fbird_connect($db, $user, $pass);
$conn2 = fbird_connect($db, $user, $pass, '', 0, 0, '', FBIRD_CONNECT_FORCE_NEW);

// $conn1 and $conn2 are now DIFFERENT connections
var_dump($conn1 === $conn2);  // bool(false)


// Use persistent connections for better performance
$db = fbird_pconnect('/path/to/database.fdb', 'SYSDBA', 'masterkey');


// Optimize repeated queries
$stmt = fbird_prepare($db, 'SELECT * FROM users WHERE id = ?');
for ($i = 1; $i <= 1000; $i++) {
    $result = fbird_execute($stmt, $i);
    // Process result
    fbird_free_result($result);
}
fbird_free_query($stmt);

$event = fbird_set_event_handler($conn, $callback, 'MY_EVENT');
$event->wait(5.0);    // Block up to 5 seconds
$event->getName();    // Get event name
$event->getCount();   // Get callback invocation count
$event->cancel();     // Cancel pending wait


use Firebird\EventPoller;

$conn = fbird_connect('/path/to/database.fdb', 'SYSDBA', 'masterkey');
$event = fbird_set_event_handler($conn, function($name) {
    echo "Event received: $name\n";
    return true;  // Continue listening
}, 'MY_EVENT');

// Create poller with auto-detected strategy
$poller = EventPoller::create($event);

// Or specify strategy explicitly
$poller = EventPoller::create($event, 'process');  // Most reliable
$poller->setConnectionDetails('/path/to/database.fdb', 'SYSDBA', 'masterkey', ['MY_EVENT'], $callback);

// Poll with 5 second timeout
$result = $poller->poll(5000);

if ($result === FBIRD_EVENT_TIMEOUT) {
    echo "Timeout - no events\n";
}

$poller->free();
fbird_close($conn);


// Prepared statements - RECOMMENDED
$stmt = fbird_prepare($db, "SELECT * FROM users WHERE username = ? AND active = ?");
$result = fbird_execute($stmt, $username, 1);

// Inline parameters
$result = fbird_query($db, "SELECT * FROM accounts WHERE id = ?", $accountId);


// SQL Injection vulnerable - NEVER concatenate user input!
$result = fbird_query($db, "SELECT * FROM users WHERE username = '$username'");

// Even with addslashes() - NOT safe for Firebird!
$result = fbird_query($db, "SELECT * FROM users WHERE username = '" . addslashes($username) . "'");


// Escape single quotes (' → '') for safe SQL string literals
$safe = fbird_escape_string($userInput);
$sql = "SELECT * FROM users WHERE notes LIKE '%" . $safe . "%'";
bash
# Install dependencies (PHP 8.2+)
sudo apt-get update
sudo apt-get install php8.3-dev firebird-dev firebird3.0-server

# Build extension
git clone https://github.com/satwareAG/php-firebird.git
cd php-firebird
phpize
CPPFLAGS=-I/usr/
batch
REM Prerequisites: Visual Studio 2019+ with C++ tools, Git for Windows

REM Download PHP SDK
git clone https://github.com/Microsoft/php-sdk-binary-tools.git c:\php-sdk
cd c:\php-sdk

REM Prepare build environment (x64)
phpsdk-vs16-x64.bat

REM Setup build tree for PHP 8.3+
phpsdk_buildtree php83
git clone https://github.com/php/php-src.git
cd php-src
git checkout PHP-8.3

REM Get dependencies
phpsdk_deps --update --branch 8.3

REM Download extension source
mkdir ..\pecl
git clone https://github.com/satwareAG/php-firebird.git ..\pecl\firebird

REM Build (adjust Firebird path as needed)
buildconf --force
configure --disable-all --enable-cli --with-firebird="shared,C:\Program Files\Firebird\5_0"
nmake
bash
# Install dependencies
brew install [email protected] firebird

# Build extension
git clone https://github.com/satwareAG/php-firebird.git
cd php-firebird
phpize
./configure --with-firebird=$(brew --prefix firebird)
make all test

# Install
sudo make install
echo "extension=firebird.so" >> $(php --ini | grep "Scan for" | cut -d: -f2 | tr -d ' ')/firebird.ini
bash
# Build both extensions first
phpize && ./configure && make
cd pdo_fbird && phpize && ./configure && make && cd ..

# All tests (loads both firebird.so AND pdo_fbird.so)
php run-tests.php \
  -d extension=modules/firebird.so \
  -d extension=pdo_fbird/modules/pdo_fbird.so \
  -p $(which php) \
  tests/

# Specific test file
php run-tests.php \
  -d extension=modules/firebird.so \
  -d extension=pdo_fbird/modules/pdo_fbird.so \
  -p $(which php) \
  tests/fbird_connect_001.phpt
bash
# Create test database ( masterkey
CREATE DATABASE '/tmp/test.fdb';
EXIT;

# Run extension tests
export TEST_DB_PATH=/tmp/test.fdb
export TEST_DB_USER=SYSDBA  
export TEST_DB_PASS=masterkey
php run-tests.php -d extension=modules/firebird.so tests/
bash
# Use specific PHP version
phpize8.3  # Ubuntu/Debian versioned phpize
./configure --with-php-config=/usr/bin/php-config8.3
neon
parameters:
    scanFiles:
        - vendor/satwareag/php-firebird-stubs/firebird-stubs.php
        - vendor/satwareag/php-firebird-stubs/firebird-classes.php
xml
<stubs>
    <file name="vendor/satwareag/php-firebird-stubs/firebird-stubs.php"/>
    <file name="vendor/satwareag/php-firebird-stubs/firebird-classes.php"/>
</stubs>
bash
# Download from GitHub Releases (example: Linux x86_64 glibc)
wget https://github.com/satwareAG/php-firebird/releases/download/v13.2.0/php-firebird-13.2.0-php84-nts-linux-x86_64.tar.gz

# Extract to PHP extension directory
EXTDIR=$(php -r 'echo ini_get("extension_dir");')
sudo tar -xzf php-firebird-13.2.0-php84-nts-linux-x86_64.tar.gz -C "$EXTDIR" --strip-components=1

# Enable and verify (both extensions 
bash
# Ubuntu 20.04 / Debian 11 (ondrej/php PPA)
sudo apt-get install -y software-properties-common
sudo add-apt-repository -y ppa:ondrej/php  # Ubuntu
# For Debian: https://packages.sury.org/php/README.txt
sudo apt-get update
sudo apt-get install -y php8.4-cli php8.4-common

# Rocky Linux 8/9 / AlmaLinux 8/9 (remi repo)
sudo dnf install -y https://rpms.remirepo.net/enterprise/remi-release-$(rpm -E %rhel).rpm
sudo dnf module reset php
sudo dnf module enable php:remi-8.4
sudo dnf install -y php php-cli