1. Go to this page and download the library: Download buildql/query-builder 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/ */
buildql / query-builder example snippets
BuildQL\Database\Query\DB;
// Manual configuration
DB::setConnection(
'localhost', // host
'root', // username
'', // password
'my_database',// database (optional)
3306 // port (optional, default: 3306)
);
// Now you can use the query builder
$users = DB::table('users')->get();
uildQL\Database\Query\DB;
// Automatically loads from .env in project's root if exists
DB::boot();
// Or specify custom path (directory only, not .env file)
DB::boot("/path/to/your/env/directory");
public static function setConnection(
string $server,
string $username,
string $pass,
?string $database = null,
int $port = 3306
): void
public static function boot(?string $absoluteEnvPath = null): void
// Load from project root
DB::boot();
// Load from custom directory
DB::boot("/var/www/config");
// If path contains .env filename, it will be automatically removed
DB::boot("/var/www/config/.env"); // Works the same as above
public static function table(string $table, ?string $database = null): Builder
$query = DB::table('users');
$query = DB::table('users:u'); // With alias
$query = DB::table('users', 'other_db'); // Different database
public static function raw(string $sql, array $bind = []): mixed
// SELECT query
$results = DB::raw("SELECT * FROM users WHERE age > ?", [18]);
// INSERT query
$success = DB::raw("INSERT INTO users (name, email) VALUES (?, ?)", ['John', '[email protected]']);
// UPDATE query
$success = DB::raw("UPDATE users SET status = ? WHERE id = ?", ['active', 1]);
// ❌ Wrong way to bind values
$success = DB::raw("UPDATE users SET status = :active WHERE id = :id", ['active' => 'active', 'id' => 1]);
public static function setDatabaseGlobally(string $database): void
DB::setDatabaseGlobally('my_app');
public static function getGlobalDatabase(): ?string
public function leftJoin(string $table, string $primaryKey, string $foreignKey): self
// Get all users, including those without profiles
DB::table('users')
->leftJoin('profiles', 'users.id', 'profiles.user_id')
->select(['users.name', 'profiles.bio'])
->get();
public function rightJoin(string $table, string $primaryKey, string $foreignKey): self
// Generate all combinations of sizes and colors
DB::table('sizes')
->crossJoin('colors')
->get();
public function groupBy(string ...$columns): self
// Group by single column
DB::table('orders')
->select(['user_id', 'count(*):total_orders'])
->groupBy('user_id')
->get();
// Group by multiple columns
DB::table('sales')
->select(['country', 'city', 'sum(amount):total'])
->groupBy('country', 'city')
->get();
public function having(string $column, $operator, $value = null): self
// Users with more than 5 orders
DB::table('orders')
->select(['user_id', 'count(*):order_count'])
->groupBy('user_id')
->having('order_count', '>', 5)
->get();
// Multiple HAVING conditions
DB::table('sales')
->select(['product_id', 'sum(amount):total', 'count(*):sales_count'])
->groupBy('product_id')
->having('total', '>', 1000)
->having('sales_count', '>=', 10)
->get();
public function orHaving(string $column, $operator, $value = null): self
public function limit(int $limit, ?int $offset = null): self
// Get first 10 records
DB::table('users')->limit(10)->get();
// Skip 20 records, get next 10 (pagination)
DB::table('users')->limit(10, 20)->get();
public function offset(int $offset): self
// Page 3 of results (20 per page)
DB::table('posts')
->orderBy('created_at', 'DESC')
->limit(20)
->offset(40)
->get();
public function get(array $columns = ["*"]): array
// Get all users
$users = DB::table('users')->get();
// Get specific columns
$users = DB::table('users')->get(['id', 'name', 'email']);
// With WHERE condition
$activeUsers = DB::table('users')
->where('status', 'active')
->get();
// Result format:
// [
// ['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
// ['id' => 2, 'name' => 'Jane', 'email' => '[email protected]'],
// ]
public function all(): array
$allUsers = DB::table('users')->all();
public function first(array $columns = ['*']): array
// Get first user
$user = DB::table('users')->first();
// Result: ['id' => 1, 'name' => 'John', ...]
// Get first matching record
$admin = DB::table('users')
->where('role', 'admin')
->first();
// Specific columns
$user = DB::table('users')->first(['id', 'name']);
public function find(int $id, array $columns = ['*']): array
// Find user by ID
$user = DB::table('users')->find(1);
// With specific columns
$user = DB::table('users')->find(1, ['name', 'email']);
// Works with table aliases
$user = DB::table('users:u')
->join('profiles:p', 'u.id', 'p.user_id')
->find(1, ['u.name', 'p.bio']);
// Update single record
DB::table('users')
->where('id', 1)
->update([
'name' => 'John Smith',
'updated_at' => date('Y-m-d H:i:s')
]);
// Update multiple records
DB::table('users')
->where('status', 'pending')
->update(['status' => 'active']);
// Update with multiple conditions
DB::table('orders')
->where('status', 'pending')
->where('created_at', '<', date('Y-m-d', strtotime('-30 days')))
->update(['status' => 'cancelled']);
// ❌ wrong way without where condition. In that case exception will be thrown
DB::table('users')
->update(['status' => 'active']);
public function delete(): bool
// Delete single record
DB::table('users')
->where('id', 1)
->delete();
// Delete multiple records
DB::table('logs')
->where('created_at', '<', date('Y-m-d', strtotime('-90 days')))
->delete();
// Delete with multiple conditions
DB::table('spam')
->where('reported', '>', 5)
->whereNull('verified_at')
->delete();
// ❌ Wrong way without where condition. In that case exception will be thrown
DB::table('users')
->delete();
public function insertOrUpdate(array $data, array $where = []): bool
// Update if exists, insert if not
DB::table('settings')->insertOrUpdate(
['value' => 'dark'],
['key' => 'theme']
);
// With multiple conditions
DB::table('user_preferences')->insertOrUpdate(
[
'user_id' => 1,
'preference' => 'notifications',
'value' => 'enabled'
],
[
'user_id' => 1,
'preference' => 'notifications'
]
);
// With whereIn condition
DB::table('inventory')->insertOrUpdate(
['stock' => 100],
['product_id' => [1, 2, 3]] // Array value = whereIn
);
public function toRawSql(): string
$sql = DB::table('users')
->where('status', 'active')
->where('age', '>', 18)
->toRawSql();
// Result: "SELECT * FROM `users` WHERE `status` = ? AND `age` > ?"
// Complex query preview
$sql = DB::table('orders:o')
->join('users:u', 'o.user_id', 'u.id')
->select(['u.name', 'count(o.id):total'])
->where('o.status', 'completed')
->groupBy('u.id')
->having('total', '>', 5)
->orderBy('total', 'DESC')
->toRawSql();
// Result: SELECT `u`.`name`, count(`o`.`id`) as `total` FROM `orders` as `o` INNER JOIN `users` as `u` ON `o`.`user_id` = `u`.`id` WHERE `o`.`status` = ? GROUP BY `u`.`id` HAVING `total` > ? ORDER BY `total` DESC
// Register new user
DB::table('users')->insert([
'name' => 'Alice Johnson',
'email' => '[email protected]',
'password' => password_hash('secure_password', PASSWORD_DEFAULT),
'role' => 'user',
'created_at' => date('Y-m-d H:i:s')
]);
// Authenticate user
$user = DB::table('users')
->where('email', '[email protected]')
->whereNotNull('email_verified_at')
->first();
if ($user && password_verify('secure_password', $user['password'])) {
// Login successful
}
// Get user with profile
$userProfile = DB::table('users:u')
->leftJoin('profiles:p', 'u.id', 'p.user_id')
->where('u.id', 1)
->first([
'u.id', 'u.name', 'u.email',
'p.bio', 'p.avatar', 'p.location'
]);
// Published posts with author info
$posts = DB::table('posts:p')
->join('users:u', 'p.author_id', 'u.id')
->leftJoin('categories:c', 'p.category_id', 'c.id')
->select([
'p.id', 'p.title', 'p.slug', 'p.excerpt',
'p.published_at', 'u.name:author_name',
'c.name:category_name'
])
->whereNotNull('p.published_at')
->where('p.status', 'published')
->orderBy('p.published_at', 'DESC')
->limit(10)
->get();
// Post with comments count
$post = DB::table('posts:p')
->leftJoin('comments:c', 'p.id', 'c.post_id')
->select(['p.*', 'count(c.id):comment_count'])
->where('p.slug', 'my-first-post')
->groupBy('p.id')
->first();
// ✅ SAFE - Uses prepared statements (Recommended way)
$email = $_POST['email'];
$user = DB::table('users')->where('email', $email)->first();
// ❌ NEVER DO THIS
$user = DB::raw("SELECT * FROM users WHERE email = '$email'"); // SQL Injection risk!
// ✅ SAFE - If you want to manually write query then replace actual value to placeholder (?)
// and attach value to second param of raw() method as an array Like
$user = DB::raw("SELECT * FROM users WHERE email = ?", [$email]); // No SQL Injection risk!
use BuildQL\Database\Query\DB;
use BuildQL\Database\Query\Exception\BuilderException;
try {
$users = DB::table('users')->where('age', '>', 18)->get();
} catch (BuilderException $e) {
// Get detailed error message with trace
echo $e->getErrorMessage();
// Output: "Query Execution Failed: Table 'database.users' doesn't exist - Check your code in app.php at line 25"
// Log error
error_log($e->getErrorMessage());
}
// With trace (default behavior)
throw new BuilderException("Error message"); // Shows: "Error message - Check your code in file.php at line 25"
// Without trace (useful for production)
throw new BuilderException("Error message", false); // Shows: "Error message"
// Connection is not established right now.
// Connection already established. Connection will not be established more than once.
// Connection Failed Due to : Access denied for user
// Where method is not optional in update case
// Where method is not optional in delete case
// Invalid column name : user_id;DROP TABLE users
// Query Preparation Failed: You have an error in your SQL syntax
// Query Execution Failed: You have an error in your SQL syntax
// $values parameter must be a non-empty array
// Select method must be contain a proper non-empty array of columns name
// Invalid join clause (INVALID_TYPE)