PHP code example of progrmanial / simple-mysqli-fork
1. Go to this page and download the library: Download progrmanial/simple-mysqli-fork 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/ */
progrmanial / simple-mysqli-fork example snippets
// All the enterprise data types you need
$table->increments('id') // Auto-increment primary key
->uuid('external_id') // UUID storage (36 chars)
->ulid('session_id') // ULID storage (26 chars)
->ipAddress('client_ip') // IPv4/IPv6 (45 chars)
->macAddress('device_mac') // MAC address (17 chars)
->json('preferences') // JSON data storage
->morphs('taggable'); // Polymorphic relationships
// Precise numeric handling
$table->float('rating', 3, 2) // Single precision: 0.00-9.99
->double('coordinates', 10, 8) // Double precision coordinates
->decimal('price', 10, 2) // Exact monetary values
->tinyInteger('priority') // -128 to 127
->smallInteger('count') // -32,768 to 32,767
->mediumInteger('views') // -8,388,608 to 8,388,607
->bigInteger('total_bytes'); // Large integers
// Comprehensive temporal and binary support
$table->date('birth_date') // Date only (no time)
->time('meeting_time', 3) // Time with microsecond precision
->year('copyright_year') // Year storage (1901-2155)
->binary('file_data') // Binary data storage
->char('country_code', 2); // Fixed-length strings
// String types with different purposes
$table->string('email', 150) // Email addresses
->string('password', 255) // Encrypted passwords
->char('currency', 3) // Currency codes (USD, EUR)
->text('bio') // User biography
->mediumText('post_content') // Blog posts
->longText('system_logs'); // System logs
// All integer types support unsigned() modifier
$table->tinyInteger('age')->unsigned() // 0 to 255
->smallInteger('port')->unsigned() // 0 to 65535
->mediumInteger('population')->unsigned() // 0 to 16M
->integer('user_id')->unsigned() // 0 to 4B
->bigInteger('bytes_transferred')->unsigned(); // 0 to 18E18
// ❌ Invalid: unsigned() only works with numeric types
$table->string('name')->unsigned(); // Error!
// ❌ Invalid: useCurrent() only works with timestamp types
$table->string('name')->useCurrent(); // Error!
// ❌ Invalid: columnCharset() only works with string types
$table->integer('count')->columnCharset('utf8mb4'); // Error!
$schema->createTable('users', function($table) {
$table->increments('id');
// Name fields with proper charset
$table->string('first_name', 50)
->comment('User first name')
->columnCharset('utf8mb4')
->columnCollation('utf8mb4_unicode_ci');
$table->string('last_name', 50)
->comment('User last name')
->columnCharset('utf8mb4')
->columnCollation('utf8mb4_unicode_ci');
// Email with case-insensitive collation
$table->string('email', 150)
->unique()
->comment('User email address')
->columnCharset('utf8mb4')
->columnCollation('utf8mb4_general_ci');
// Secure password field
$table->string('password', 255)
->comment('Encrypted password hash');
// Numeric fields with constraints
$table->tinyInteger('age')
->unsigned()
->nullable()
->comment('User age in years');
$table->decimal('account_balance', 10, 2)
->unsigned()
->default(0.00)
->comment('Account balance in USD');
// Timestamp fields with automatic values
$table->timestamp('created_at')
->useCurrent()
->comment('Account creation time');
$table->timestamp('updated_at')
->useCurrent()
->useCurrentOnUpdate()
->comment('Last profile update');
$table->timestamp('last_login_at')
->nullable()
->comment('Last login timestamp');
// Audit columns (invisible in MySQL 8.0+)
$table->json('audit_trail')
->invisible()
->nullable()
->comment('Internal audit information');
});
// Enterprise-grade column customization
$table->string('title', 200)
->comment('SEO-optimized page title') // Self-documenting schemas
->columnCharset('utf8mb4') // Custom character sets
->columnCollation('utf8mb4_unicode_ci') // Specific collations
->nullable() // Allow NULL values
->default('Untitled') // Default values
->after('slug') // Position after column
->invisible(); // Hidden from SELECT *
// Numeric modifiers
$table->decimal('balance', 15, 2)
->unsigned() // Only positive values
->default(0.00)
->comment('Account balance in USD');
// Timestamp helpers
$table->timestamp('created_at')->useCurrent() // DEFAULT CURRENT_TIMESTAMP
->timestamp('updated_at')->useCurrentOnUpdate() // ON UPDATE CURRENT_TIMESTAMP
->timestamp('deleted_at')->nullable(); // Soft deletes
// Migration: "create_users_table"
// ✨ Auto-generates complete user table with modern features
php artisan migration:create create_users_table
// Migration: "add_email_to_customers"
// ✨ Auto-detects VARCHAR(255) for email + unique constraint
php artisan migration:create add_email_to_customers
// Migration: "add_is_active_to_posts"
// ✨ Auto-detects BOOLEAN type for is_* fields
php artisan migration:create add_is_active_to_posts
// Intelligently generated based on migration name
public function up(): void
{
$this->createTable('users', function($table) {
$table->increments('id');
$table->string('name')->comment('Full name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->date('birth_date')->nullable();
$table->enum('status', ['active', 'inactive', 'pending'])->default('active');
$table->json('preferences')->nullable();
$table->ipAddress('last_login_ip')->nullable();
$table->rememberToken(); // Laravel-style auth token
$table->timestamps(); // created_at, updated_at
$table->softDeletes(); // deleted_at
});
}
// All identifiers properly escaped
$table->string('user-name') // Becomes `user-name` in SQL
->comment("User's full name"); // Becomes COMMENT 'User\'s full name'
// All values parameterized
$table->enum('status', ["'admin'", '"user"']) // Properly escaped enum values
->default("'pending'"); // Safe default handling
// 65+ MySQL reserved words detected
$table->string('select'); // ❌ Error: 'select' is a MySQL reserved word
// Length validation with helpful messages
$table->string('title', 70000); // ❌ Error: VARCHAR length must be between 1 and 65535, got 70000
// Type compatibility checking
$table->json('data')->unsigned(); // ❌ Error: unsigned() can only be used with numeric columns
$schema->createTable('search_index', function($table) {
$table->increments('id');
$table->string('title', 200);
$table->text('content');
$table->string('category', 50);
$table->timestamps();
// Regular index
$table->index(['category'], 'category_idx');
// Composite index
$table->index(['category', 'created_at'], 'category_date_idx');
// Unique index
$table->unique(['title'], 'unique_title');
// Full-text index
$table->fullTextIndex(['title', 'content'], 'search_fulltext');
// Partial index (MySQL 8.0+)
$table->partialIndex(['title'], 'active_titles', 'status = "active"');
});
$schema->createTable('analytics', function($table) {
$table->increments('id');
// Geographic data
$table->point('location'); // POINT type for coordinates
$table->polygon('area'); // POLYGON type for regions
$table->lineString('route'); // LINESTRING type for paths
// Large objects
$table->mediumText('report'); // Up to 16MB text
$table->longText('log_data'); // Up to 4GB text
$table->mediumBlob('image'); // Up to 16MB binary
$table->longBlob('video'); // Up to 4GB binary
// Network data
$table->ipAddress('client_ip'); // IPv4/IPv6
$table->macAddress('device_mac'); // MAC address
// JSON and document storage
$table->json('config'); // JSON data
$table->jsonb('metadata'); // Binary JSON (if supported)
// Time-series data
$table->timestamp('event_time', 6); // Microsecond precision
$table->time('duration', 3); // Millisecond precision
$table->year('fiscal_year'); // Year only
});
use SimpleMDB\DatabaseFactory;
use SimpleMDB\SchemaBuilder;
// Connect to database
$db = DatabaseFactory::create('pdo', 'localhost', 'root', 'password', 'database');
$schema = new SchemaBuilder($db);
// Create modern table with enterprise features
$schema->increments('id')
->string('name')->comment('User full name')
->string('email')->unique()
->ipAddress('last_ip')->nullable()
->json('preferences')->nullable()
->enum('status', ['active', 'inactive'])->default('active')
->timestamps()
->softDeletes()
->createTable('users');
use SimpleMDB\Migrations\MigrationManager;
// Initialize migration manager
$migrations = new MigrationManager($db);
// Set migration directory (optional)
$migrations->setMigrationDirectory('./database/migrations');
// Set migration table name (optional)
$migrations->setMigrationTable('schema_migrations');
// Run all pending migrations
$migrations->migrate();
// Run specific number of migrations
$migrations->migrate(5);
// Run migrations with output
$migrations->migrate(null, true); // true for verbose output
// Check migration status
$status = $migrations->status();
foreach ($status as $migration) {
echo sprintf("%-40s %s\n", $migration['name'], $migration['status']);
}
// Check if migrations are pending
if ($migrations->hasPendingMigrations()) {
echo "Pending migrations found!\n";
}
use SimpleMDB\Migrations\Migration;
class AddEmailIndexToUsers extends Migration
{
public function up(): void
{
$this->addIndex('users', ['email'], 'users_email_index');
}
public function down(): void
{
$this->dropIndex('users', 'users_email_index');
}
}
// Rollback last migration
$migrations->rollback();
// Rollback specific number of migrations
$migrations->rollback(3);
// Rollback to specific migration
$migrations->rollbackTo('20240101_120000_CreateUsersTable');
// Reset all migrations (dangerous!)
$migrations->reset();
// Detailed migration history
$history = $migrations->history();
foreach ($history as $migration) {
echo sprintf(
"%-40s %-10s %s\n",
$migration['name'],
$migration['status'],
$migration['executed_at'] ?? 'Pending'
);
}
// Check if specific migration exists
if ($migrations->hasMigration('create_users_table')) {
echo "Users table migration exists\n";
}
// Get migration file path
$path = $migrations->getMigrationPath('create_users_table');
// Run migrations in transaction
$migrations->migrateInTransaction();
// Rollback migrations in transaction
$migrations->rollbackInTransaction(2);
// Dry run (show what would be executed)
$migrations->dryRun();
// Migration with seeding
class CreateCategoriesTable extends Migration
{
public function up(): void
{
$this->createTable('categories', function($table) {
$table->increments('id');
$table->string('name', 100)->unique();
$table->string('slug', 100)->unique();
$table->text('description')->nullable();
$table->boolean('active')->default(true);
$table->timestamps();
});
// Seed initial data
$this->seed();
}
public function down(): void
{
$this->dropIfExists('categories');
}
private function seed(): void
{
$categories = [
['name' => 'Technology', 'slug' => 'technology', 'description' => 'Tech products'],
['name' => 'Fashion', 'slug' => 'fashion', 'description' => 'Fashion items'],
['name' => 'Home', 'slug' => 'home', 'description' => 'Home products'],
];
foreach ($categories as $category) {
$this->insert('categories', $category);
}
}
}
use SimpleMDB\Migrations\Migration;
class ExampleMigration extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// Migration code here
}
/**
* Reverse the migrations.
*/
public function down(): void
{
// Rollback code here
}
}
public function up(): void
{
// ✅ Always check if table exists
if (!$this->hasTable('users')) {
$this->createTable('users', function($table) {
// Table definition
});
}
// ✅ Check if column exists before adding
if (!$this->hasColumn('users', 'email')) {
$this->addColumn('users', 'email', 'string', 150);
}
// ✅ Use transactions for multiple operations
$this->beginTransaction();
try {
$this->addColumn('users', 'status', 'string', 20);
$this->addIndex('users', ['status']);
$this->commit();
} catch (Exception $e) {
$this->rollback();
throw $e;
}
}
public function down(): void
{
// ✅ Always provide proper rollback
$this->dropColumn('users', 'email');
// ✅ Check before dropping
if ($this->hasTable('temporary_table')) {
$this->dropTable('temporary_table');
}
// ✅ Drop indexes before dropping columns
$this->dropIndex('users', 'users_email_index');
$this->dropColumn('users', 'email');
}
use SimpleMDB\Migrations\MigrationManager;
$migrations = new MigrationManager($db);
// Create intelligent migration
$file = $migrations->create('create_blog_posts_table');
// ✨ Generates context-aware template with modern data types
// Run migrations
$migrations->migrate();
// Check status
foreach ($migrations->status() as $migration) {
echo "{$migration['name']}: {$migration['status']}\n";
}
use SimpleMDB\SimpleQuery;
// Complex queries with modern features
$posts = SimpleQuery::create()
->select(['id', 'title', 'status', 'created_at'])
->from('blog_posts')
->where('status IN ?', [['published', 'featured']])
->whereJsonContains('metadata->tags', 'php')
->orderBy('created_at DESC')
->limit(10)
->execute($db);
// Create polymorphic relationship in one line
$schema->increments('id')
->text('content')
->morphs('commentable') // Creates commentable_id + commentable_type + index
->timestamps()
->createTable('comments');