1. Go to this page and download the library: Download solophp/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/ */
use Solo\QueryBuilder\Facade\Query;
use ExampleCache;
// Global cache for all Query instances (TTL 600s)
Query::enableCache(new ExampleCache(), 600);
// Local override (TTL 300s)
$query = $query->withCache(new ExampleCache(), 300);
$users = $query->from('users')->getAllAssoc();
// Disable global cache entirely
Query::disableCache();
use Solo\QueryBuilder\Facade\Query;
use Solo\QueryBuilder\Executors\PdoExecutor\PdoExecutor;
use Solo\QueryBuilder\Executors\PdoExecutor\Connection;
use Solo\QueryBuilder\Executors\PdoExecutor\Config;
use Solo\QueryBuilder\Factory\BuilderFactory;
use Solo\QueryBuilder\Factory\GrammarFactory;
// Create factories
$grammarFactory = new GrammarFactory();
// Create PDO executor
$config = new Config(
'localhost', // host
'username', // username
'password', // password
'database', // database
PDO::FETCH_ASSOC, // fetchMode
'mysql', // driver
null, // port (optional)
[] // options (optional)
);
$connection = new Connection($config);
$executor = new PdoExecutor($connection);
// Creating a BuilderFactory with executor
$builderFactory = new BuilderFactory($grammarFactory, $executor, 'mysql');
// Creating a Query instance
$query = new Query($builderFactory);
// Build a query without executing
[$sql, $bindings] = $query->from('users')
->select('id', 'name')
->where('status = ?', 'active')
->build();
// Now you have the SQL string and parameter bindings
echo $sql;
// SELECT `id`, `name` FROM `users` WHERE status = ?
print_r($bindings);
// ['active']
// Set MySQL as default grammar
$query->setDatabaseType('mysql');
// Set PostgreSQL as default grammar
$query->setDatabaseType('postgresql'); // or 'postgres', 'pgsql'
// Set SQLite as default grammar
$query->setDatabaseType('sqlite');
// Select all records from table
$allUsers = $query->from('users')->getAllAssoc();
// Select specific columns
$users = $query->from('users')
->select('id', 'name', 'email')
->getAllAssoc();
// Use DISTINCT to select only unique values
$uniqueCities = $query->from('users')
->select('city')
->distinct()
->getAllAssoc();
// WHERE conditions
$activeUsers = $query->from('users')
->where('status = ?', 'active')
->getAllAssoc();
// Multiple conditions
$recentActiveUsers = $query->from('users')
->where('status = ?', 'active')
->where('created_at > ?', '2023-01-01')
->getAllAssoc();
// WHERE IN condition
$specificUsers = $query->from('users')
->whereIn('id', [1, 2, 3])
->getAllAssoc();
// OR WHERE IN condition
$usersWithRoles = $query->from('users')
->where('status = ?', 'active')
->orWhereIn('role', ['admin', 'editor'])
->getAllAssoc();
// Sorting
$sortedUsers = $query->from('users')
->orderBy('name') // ASC by default
->addOrderBy('created_at', 'DESC') // additional sorting
->getAllAssoc();
// Limit and offset
$paginatedUsers = $query->from('users')
->limit(10, 100) // 10 records starting from offset 100
->getAllAssoc();
// Pagination with page
$paginatedUsers = $query->from('users')
->paginate(25, 1) // 25 records per page, page 1
->getAllAssoc();
// Get a single record
$user = $query->from('users')
->where('id = ?', 1)
->getAssoc();
// Get records as objects
$userObjects = $query->from('users')
->where('status = ?', 'active')
->getAllObj();
// Get a single value
$count = $query->from('users')
->select('COUNT(*) as count')
->getValue();
// Get an array of email addresses
$emails = $query->from('users')
->select('id', 'email', 'name')
->where('status = ?', 'active')
->getColumn('email');
// Result: ['[email protected]', '[email protected]', '[email protected]']
// Get an associative array of [id => name]
$userNames = $query->from('users')
->select('id', 'name')
->getColumn('name', 'id');
// Result: [1 => 'John', 2 => 'Jane', 3 => 'Bob']
// Basic HAVING
$orderStats = $query->from('orders')
->select('user_id', '{COUNT(*) as order_count}')
->groupBy('user_id')
->having('order_count > ?', 5)
->getAllAssoc();
// HAVING IN
$orderStats = $query->from('orders')
->select('user_id', '{COUNT(*) as order_count}')
->groupBy('user_id')
->havingIn('user_id', [1, 2, 3])
->getAllAssoc();
// Combined HAVING conditions
$orderStats = $query->from('orders')
->select('user_id', '{COUNT(*) as order_count}')
->groupBy('user_id')
->having('order_count > ?', 10)
->orHavingIn('user_id', [5, 6, 7])
->getAllAssoc();
// Get prices from products
$prices = $query->from('products')
->select('id', 'name', 'price')
->where('category_id = ?', 5)
->getColumn('price');
// Result: [19.99, 24.99, 14.50]
// Count the number of records
$totalUsers = $query->from('users')->count();
// Count records with conditions
$activeUserCount = $query->from('users')
->where('status = ?', 'active')
->count();
// Count specific fields or unique values
$emailCount = $query->from('users')->count('email'); // Count of non-NULL emails
$uniqueCities = $query->from('users')->count('city', true); // Count of unique cities
// Raw expressions in select
$users = $query->from('users')
->select('id', 'name', '{CONCAT(first_name, " ", last_name) as full_name}')
->getAllAssoc();
// Aggregation functions
$userStats = $query->from('orders')
->select('user_id', '{COUNT(*) as order_count}', '{SUM(amount) as total_spend}')
->groupBy('user_id')
->having('total_spend > ?', 1000)
->getAllAssoc();
// Date functions
$ordersByMonth = $query->from('orders')
->select('id', '{DATE_FORMAT(created_at, "%Y-%m") as month}', 'status')
->where('created_at >= ?', '2023-01-01')
->getAllAssoc();
// Only apply where clause if condition is true
$email = '[email protected]';
$status = null;
$users = $query->from('users')
->when($email !== null, function($q) use ($email) {
return $q->where('email = ?', $email);
})
->when($status !== null, function($q) use ($status) {
return $q->where('status = ?', $status);
})
->getAllAssoc();
// Apply a default callback when condition is false
$minPrice = null;
$defaultMinPrice = 10;
$products = $query->from('products')
->when($minPrice !== null,
function($q) use ($minPrice) {
return $q->where('price >= ?', $minPrice);
},
function($q) use ($defaultMinPrice) {
return $q->where('price >= ?', $defaultMinPrice);
}
)
->getAllAssoc();
// GROUP BY with aggregate functions
$userOrderStats = $query->from('orders')
->select('user_id', '{COUNT(*) as order_count}', '{SUM(amount) as total_spend}')
->groupBy('user_id')
->having('total_spend > ?', 1000)
->getAllAssoc();
// Insert one record and get ID
$userId = $query->insert('users')
->values([
'name' => 'John Doe',
'email' => '[email protected]',
'created_at' => date('Y-m-d H:i:s')
])
->insertGetId();
// Insert one record and get affected rows
$affectedRows = $query->insert('users')
->values([
'name' => 'John Doe',
'email' => '[email protected]',
'created_at' => date('Y-m-d H:i:s')
])
->execute();
// Insert multiple records
$affectedRows = $query->insert('logs')
->values([
['user_id' => 1, 'action' => 'login', 'created_at' => date('Y-m-d H:i:s')],
['user_id' => 2, 'action' => 'logout', 'created_at' => date('Y-m-d H:i:s')]
])
->execute();