PHP code example of wowsql / wowsql-sdk

1. Go to this page and download the library: Download wowsql/wowsql-sdk 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/ */

    

wowsql / wowsql-sdk example snippets



WOWSQL\WOWSQLClient;

// Initialize client
$client = new WOWSQLClient('myproject', 'wowsql_anon_...');

// Insert a record
$user = $client->table('users')->create([
    'email' => '[email protected]',
    'name'  => 'Alice',
]);

// Query with filters
$result = $client->table('users')
    ->select('id', 'email', 'name')
    ->eq('is_active', true)
    ->orderBy('created_at', true)   // true = descending
    ->limit(10)
    ->get();

foreach ($result['data'] as $u) {
    echo $u['email'] . "\n";
}

$client->close();

$client = new WOWSQLClient(
    'myproject',              // Project slug, hostname, or full URL
    'wowsql_anon_...',        // Anonymous key (or service role key)
    'wowsqlconnect.com',      // base_domain — default, override for self-hosting
    true,                     // $secure — use HTTPS (default: true)
    30,                       // $timeout — seconds (default: 30)
    true                      // $verifySsl (default: true)
);

// All records
$result = $client->table('products')->get();

// With chained filters
$result = $client->table('products')
    ->select('id', 'name', 'price')
    ->eq('category', 'electronics')
    ->orderBy('price')            // ascending
    ->limit(20)
    ->offset(0)
    ->get();

$result['data'];    // Array of records
$result['count'];   // Records returned this page
$result['total'];   // Total matching records
$result['limit'];   // Applied limit
$result['offset'];  // Applied offset

$user = $client->table('users')->getById('550e8400-e29b-41d4-a716-446655440000');
echo $user['email'];

$product = $client->table('products')->create([
    'name'     => 'Widget Pro',
    'price'    => 29.99,
    'category' => 'tools',
    'in_stock' => true,
]);
echo $product['id'];

$records = [
    ['name' => 'Item A', 'price' => 10.00],
    ['name' => 'Item B', 'price' => 20.00],
    ['name' => 'Item C', 'price' => 30.00],
];
$results = $client->table('products')->bulkInsert($records);
echo "Inserted " . count($results) . " records";

$record = $client->table('settings')->upsert(
    ['id' => 'user-uuid', 'theme' => 'dark', 'language' => 'en'],
    'id'   // on_conflict column (default: "id")
);

$updated = $client->table('users')->update(
    '550e8400-e29b-41d4-a716-446655440000',
    ['name' => 'Alice Smith', 'updated_at' => date('c')]
);
echo $updated['name'];

$deleted = $client->table('users')->delete('550e8400-e29b-41d4-a716-446655440000');

$client->table('users')->select('id', 'email', 'name')->get();

// Chained filters (all AND by default)
$result = $client->table('orders')
    ->gte('total', 100)
    ->lte('total', 500)
    ->eq('status', 'shipped')
    ->get();

// LIKE / ILIKE
$result = $client->table('products')
    ->ilike('name', '%widget%')
    ->get();

// IN list
$result = $client->table('users')
    ->in('role', ['admin', 'manager'])
    ->get();

// NULL check
$result = $client->table('users')->isNull('deleted_at')->get();

// Date range
$result = $client->table('orders')
    ->between('created_at', '2025-01-01', '2025-12-31')
    ->get();

// Ascending
$client->table('products')->orderBy('price')->get();

// Descending (pass true)
$client->table('products')->orderBy('created_at', true)->get();

// Multiple columns
$client->table('products')
    ->order('category', 'asc')
    ->order('price', 'desc')
    ->get();

$result = $client->table('orders')
    ->select('status', 'sum(total)', 'count(*)')
    ->groupBy('status')
    ->get();

$result = $client->table('products')->limit(20)->offset(40)->get();

$result = $client->table('products')->paginate(3, 20);

$result['data'];        // Array of records
$result['page'];        // 3
$result['per_page'];    // 20
$result['total'];       // Total matching records
$result['total_pages']; // Total pages

$user = $client->table('users')->eq('email', '[email protected]')->first();
// Returns null if not found

try {
    $user = $client->table('users')->eq('email', '[email protected]')->single();
} catch (\WOWSQL\WOWSQLException $e) {
    echo "Not found or multiple records: " . $e->getMessage();
}

$total = $client->table('users')->eq('is_active', true)->count();
echo "Active users: $total";

$totalRevenue = $client->table('orders')->eq('status', 'completed')->sum('total');
$avgPrice     = $client->table('products')->eq('category', 'electronics')->avg('price');

use WOWSQL\ProjectAuthClient;

$auth = new ProjectAuthClient(
    'myproject',
    'wowsql_anon_...',
    'wowsqlconnect.com',  // base_domain
    true,                  // secure
    30,                    // timeout
    true                   // verify_ssl
);

$response = $auth->signUp(
    '[email protected]',
    'SecurePass123!',
    'Alice Smith',          // full_name (optional)
    ['plan' => 'pro']       // user_metadata (optional)
);

echo $response['access_token'];
echo $response['user']['id'];
echo $response['user']['email'];

$response = $auth->signIn('[email protected]', 'SecurePass123!');

echo $response['access_token'];
echo $response['refresh_token'];

$user = $auth->getUser($accessToken);

echo $user['id'];
echo $user['email'];
echo $user['full_name'];
echo $user['email_verified'] ? 'verified' : 'unverified';

$oauth = $auth->getOAuthAuthorizationUrl(
    'google',
    'https://myapp.com/auth/callback'   // frontend_redirect_uri
);

// Redirect browser to:
header('Location: ' . $oauth['authorization_url']);

$result = $auth->exchangeOAuthCallback(
    'google',
    $_GET['code'],
    'https://myapp.com/auth/callback'
);

echo $result['access_token'];
echo $result['user']['email'];

// Send reset email
$auth->forgotPassword('[email protected]');

// Reset with token from email link
$auth->resetPassword(
    'reset_token_from_email',
    'NewSecurePass456!'
);

// Send OTP
$auth->sendOtp('[email protected]', 'login');

// Verify OTP
$response = $auth->verifyOtp(
    '[email protected]',
    '123456',
    'login'
);
echo $response['access_token'];

$auth->sendMagicLink('[email protected]', 'login');

// Verify email from link
$result = $auth->verifyEmail('verification_token_from_email');
echo $result['success'] ? 'Verified' : 'Failed';

// Resend
$auth->resendVerification('[email protected]');

$response = $auth->refreshToken($refreshToken);
echo $response['access_token'];

// Change password
$auth->changePassword($accessToken, 'OldPass123!', 'NewPass456!');

// Update profile
$user = $auth->updateUser($accessToken, [
    'full_name'     => 'Alice Smith',
    'avatar_url'    => 'https://cdn.example.com/avatar.jpg',
    'user_metadata' => ['bio' => 'Developer'],
]);

$auth->logout($accessToken);

use WOWSQL\WOWSQLStorage;

$storage = new WOWSQLStorage(
    'myproject',
    'wowsql_anon_...',
    'wowsqlconnect.com',  // base_domain
    true,                  // secure
    60,                    // timeout
    true                   // verify_ssl
);

$bucket = $storage->createBucket('avatars', [
    'public'             => true,
    'file_size_limit'    => 5 * 1024 * 1024,  // 5 MB
    'allowed_mime_types' => ['image/jpeg', 'image/png'],
]);
echo $bucket['name'];
echo $bucket['public'] ? 'public' : 'private';

// Upload from file handle
$fp   = fopen('/local/photo.jpg', 'rb');
$file = $storage->upload('avatars', $fp, 'users/alice.jpg');
fclose($fp);
echo $file['path'];

// Upload from path
$file = $storage->uploadFromPath('/local/photo.jpg', 'avatars', 'users/alice.jpg');

// List files
$files = $storage->listFiles('avatars', 'users/', 50);
foreach ($files as $f) {
    echo $f['path'] . " (" . round($f['size'] / 1048576, 2) . " MB)\n";
}

// Download to variable
$content = $storage->download('avatars', 'users/alice.jpg');

// Download to disk
$storage->downloadToFile('avatars', 'users/alice.jpg', '/local/alice.jpg');

// Delete
$storage->deleteFile('avatars', 'users/alice.jpg');

$url = $storage->getPublicUrl('avatars', 'users/alice.jpg');
echo $url;   // https://myproject.wowsqlconnect.com/api/v1/storage/...

$rt = $client->realtime();
$rt->subscribe('messages', function ($change) {
    echo $change['event'] . ' ' . json_encode($change['new'] ?? $change['old']);
});

$channel = $rt->channel('chat');
$channel->on('broadcast', ['event' => 'typing'], function ($msg) {
    print_r($msg['payload']);
});
$channel->on('presence', [], function ($msg) use ($channel) {
    print_r($channel->presenceState());
});
$channel->subscribe();
$channel->track(['user' => 'alice']);
$channel->send('typing', ['user' => 'alice']);

// Blocking receive loop
$rt->listen();

use WOWSQL\WOWSQLSchema;

$schema = new WOWSQLSchema(
    'myproject',
    'wowsql_service_...',
    'wowsqlconnect.com',  // base_domain
    true                   // secure
);

$schema->createTable('products', [
    ['name' => 'id',         'type' => 'UUID',         'auto_increment' => true],
    ['name' => 'name',       'type' => 'VARCHAR(255)',  'nullable' => false],
    ['name' => 'price',      'type' => 'DECIMAL(10,2)', 'nullable' => false],
    ['name' => 'category',   'type' => 'VARCHAR(100)'],
    ['name' => 'metadata',   'type' => 'JSONB',         'default' => "'{}'"],
    ['name' => 'created_at', 'type' => 'TIMESTAMPTZ',   'default' => 'CURRENT_TIMESTAMP'],
], 'id', ['category', 'name']);   // primary_key, indexes

// Add a column
$schema->addColumn('products', 'sku', 'VARCHAR(50)', true);   // nullable=true

// Drop a column
$schema->dropColumn('products', 'old_field');

// Rename a column
$schema->renameColumn('products', 'sku', 'product_sku');

// Modify column type
$schema->modifyColumn('products', 'price', 'NUMERIC(12,2)', false);

// Drop table (irreversible)
$schema->dropTable('products', false);   // cascade=false

// Execute raw DDL SQL
$schema->executeSql("CREATE INDEX idx_products_category ON products (category)");
$schema->executeSql("ALTER TABLE users ADD COLUMN last_login TIMESTAMPTZ");

try {
    $result = $client->table('orders')->getById('some-id');
} catch (\WOWSQL\WOWSQLException $e) {
    echo $e->getMessage();    // Human-readable message
    echo $e->getStatusCode(); // HTTP status code (400, 401, 403, 404, 500, etc.)
    print_r($e->getResponse()); // Raw response body array
}

try {
    $storage->upload('avatars', $largeFile, 'big.mov');
} catch (\WOWSQL\StorageLimitExceededException $e) {
    echo "File too large: " . $e->getMessage();
} catch (\WOWSQL\StorageException $e) {
    echo "Storage error: " . $e->getMessage();
}

try {
    $schema->dropTable('important_table');
} catch (\WOWSQL\SchemaPermissionException $e) {
    echo "Permission denied — use a service role key";
} catch (\WOWSQL\WOWSQLException $e) {
    echo "Schema error: " . $e->getMessage();
}

[
    'data'   => [...],   // Array of records
    'count'  => 10,      // Records in this response
    'total'  => 120,     // Total matching records (from Content-Range)
    'limit'  => 20,      // Applied limit
    'offset' => 0,       // Applied offset
]

[
    'data'        => [...],
    'page'        => 2,
    'per_page'    => 20,
    'total'       => 120,
    'total_pages' => 6,
]