Download the PHP package knifelemon/easy-query without Composer
On this page you can find all versions of the php package knifelemon/easy-query. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download knifelemon/easy-query
More information about knifelemon/easy-query
Files in knifelemon/easy-query
Package easy-query
Short Description Easy-to-use PHP SQL query builder with fluent API. Designed for FlightPHP and works with any database connection.
License MIT
Informations about the package easy-query
EasyQuery
A lightweight, fluent PHP SQL query builder that generates SQL and parameters. Designed to work with any database connection (PDO, MySQLi, FlightPHP SimplePdo).
Features
- ð Fluent API - Chain methods for readable query construction
- ðĄïļ SQL Injection Protection - Automatic parameter binding with prepared statements
- ð§ Raw SQL Support - Insert raw SQL expressions with
raw() - ð Multiple Query Types - SELECT, INSERT, UPDATE, DELETE, COUNT
- ð JOIN Support - INNER, LEFT, RIGHT joins with aliases
- ðŊ Advanced Conditions - LIKE, IN, BETWEEN, comparison operators
- ð Database Agnostic - Returns SQL + params, use with any DB connection
- ðŠķ Lightweight - Minimal footprint with zero required dependencies
Installation
Via Composer
Manual Installation
Download and include the files:
Quick Start
Understanding build() Return Value
The build() method returns an array with two keys: sql and params. This separation is fundamental to how EasyQuery keeps your database safe.
What You Get
Why Split SQL and Parameters?
EasyQuery uses prepared statements - a security feature that prevents SQL injection attacks. Instead of inserting values directly into SQL (which is dangerous), we:
- Generate SQL with placeholders (
?) - The SQL structure is defined first - Keep values separate - User data stays in the
paramsarray - Let the database combine them safely - Your database driver (PDO, MySQLi) securely binds parameters
How to Use
The most common pattern is:
Why This Matters
â Dangerous (Never do this):
â Safe (EasyQuery way):
Working with Different Frameworks
EasyQuery's separation of SQL and parameters makes it compatible with any database library:
This universal approach means you can use EasyQuery with any framework or custom database setup.
Usage Examples
SELECT Queries
Basic SELECT
SELECT with Alias
php $q = Builder::table('users') ->alias('u') ->select(['u.id', 'u.name', 'p.title', 'p.content']) ->innerJoin('posts', 'u.id = p.user_id', 'p') ->where(['u.status' => 'active']) ->orderBy('p.published_at DESC') ->build();
// Result: // sql: "SELECT u.id, u.name, p.title, p.content FROM users AS u INNER JOIN posts AS p ON u.id = p.user_id WHERE u.status = ? ORDER BY p.published_at DESC" // params: ['active']
WHERE Conditions
Simple Equality
Comparison Operators
IN Operator
NOT IN Operator
BETWEEN Operator
IS NULL and IS NOT NULL
OR Conditions
Use orWhere() to add OR grouped conditions. Conditions within the same orWhere() call are joined with OR, and each group is added to the main query with AND.
INSERT Queries
INSERT with ON DUPLICATE KEY UPDATE
Use onDuplicateKeyUpdate() to handle duplicate key errors gracefully (MySQL/MariaDB only):
UPDATE Queries
DELETE Queries
COUNT Queries
Raw SQL Expressions
Use raw() when you need to insert SQL expressions directly without parameter binding:
Raw SQL with Bindings
When you need parameterized values in raw expressions:
Safe Identifiers for User Input
When column names come from user input (e.g., dynamic sorting), use safeIdentifier() to prevent SQL injection:
Safe Raw Expressions with User Input
Use rawSafe() when building raw SQL with user-provided column names:
Framework Integration
FlightPHP Integration
EasyQuery works with FlightPHP's SimplePdo by generating SQL and parameters that you pass directly to SimplePdo methods.
Legacy PHP / PDO Integration
MySQLi Integration
API Reference
Static Methods
Builder::table(string $table, string $alias = ''): Builder
Set the table name for the query. Optionally set a table alias in the same call.
Builder::raw(string $value): BuilderRaw
Create a raw SQL expression that will be inserted directly without parameter binding.
Builder::raw(string $value, array $bindings = []): BuilderRaw
Create a raw SQL expression with optional bound parameters for ? placeholders.
Builder::rawSafe(string $expression, array $identifiers, array $bindings = []): BuilderRaw
Create a raw SQL expression with safe identifier substitution. Use {placeholder} syntax for identifiers.
Builder::safeIdentifier(string $identifier): string
Validate and return a safe column/table identifier. Only allows alphanumeric, underscores, and dots.
Instance Methods
alias(string $alias): self
Set an alias for the table.
select(string|array $columns = '*'): self
Set the columns to select.
where(array $conditions): self
Add WHERE conditions. Multiple calls are combined with AND.
orWhere(array $conditions): self
Add OR WHERE conditions.
join(string $table, string $condition, string $alias = '', string $type = 'INNER'): self
Add a JOIN clause.
leftJoin(string $table, string $condition, string $alias = ''): self
Add a LEFT JOIN clause.
innerJoin(string $table, string $condition, string $alias = ''): self
Add an INNER JOIN clause.
groupBy(string $groupBy): self
Add GROUP BY clause.
orderBy(string $orderBy): self
Add ORDER BY clause.
limit(int $limit, int $offset = 0): self
Add LIMIT and optional OFFSET.
count(string $column = '*'): self
Set the query action to COUNT.
insert(array $data): self
Set the query action to INSERT with data.
update(array $data): self
Set the query action to UPDATE with data.
delete(): self
Set the query action to DELETE.
clearWhere(): self
Clear WHERE conditions and parameters (allows query builder reuse).
clearSelect(): self
Clear SELECT columns (reset to default '*').
clearJoin(): self
Clear all JOIN clauses.
clearGroupBy(): self
Clear GROUP BY clause.
clearOrderBy(): self
Clear ORDER BY clause.
clearLimit(): self
Clear LIMIT and OFFSET.
clearAll(): self
Clear all query conditions (reset builder to initial state).
build(): array
Build and return the query as ['sql' => string, 'params' => array].
get(): array
Alias for build().
buildSQL(): string
Build and return only the SQL string (for SELECT queries).
getParams(): array
Get the parameter array for binding.
Advanced Examples
Complex JOIN with Multiple Conditions
Dynamic Query Building
Query Builder Reuse
The query builder can be reused by clearing specific conditions or resetting entirely. This is useful when you need to execute similar queries with different parameters.
Clear Methods Usage
Practical Example: Pagination with Reuse
Batch Insert Helper
Security
This library uses prepared statements with parameter binding to protect against SQL injection attacks. Parameters are never directly concatenated into SQL strings.
Safe Parameter Binding
Safe Column Names from User Input
When column names come from user input (e.g., sorting, aggregation), use these safety methods:
Allowed Identifier Characters
safeIdentifier() and rawSafe() only allow:
- Letters (a-z, A-Z)
- Numbers (0-9)
- Underscores (_)
- Dots (.) for table.column notation
Any other characters will throw an InvalidArgumentException.
Debugging with Tracy
EasyQuery provides automatic Tracy Debugger integration with a beautiful custom panel. No setup required! Just install Tracy and use EasyQuery - the debug panel will automatically appear.
Automatic Setup
How It Works
- Auto-initialization: First
Builderinstantiation automatically initializes Tracy logging - Zero configuration: Just have Tracy installed and it works
- Automatic logging: Every
build()call is logged to the custom Tracy panel
Tracy Panel Features
The custom Tracy panel shows:
- Summary Cards: Total queries, breakdown by type (SELECT, INSERT, UPDATE, DELETE, COUNT)
- Query List: Each query with:
- Action type badge (color-coded)
- Generated SQL (syntax highlighted)
- Parameters array
- Expandable details (table, where, joins, order, limit, etc.)
- Timestamp
Install Tracy:
If Tracy is not installed, EasyQuery works normally without any debug output.
Testing
Requirements
- PHP >= 7.4
- PDO or MySQLi extension (for database connectivity)
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Credits
Created and maintained by KnifeLemon
Changelog
See CHANGELOG.md for version history.
Support
If you encounter any issues or have questions, please open an issue on GitHub.