Query Builder - SQL Query Execution

PowerLite PDO's QueryBuilder offers a streamlined approach to SQL query execution. Learn the essentials of creating and executing SQL queries.

This page provides a comprehensive guide on how to use the QueryBuilder::query() method to execute SQL queries using prepared or non-prepared SQL strings.

Table of Contents

Loading the QueryBuilder Class

Before you can use the QueryBuilder class, you need to load it within the Dependency Injection (DI) container.

use Migliori\PowerLitePdo\Query\QueryBuilder;

$container = require_once __DIR__ . '/../src/bootstrap.php';
$queryBuilder = $container->get(QueryBuilder::class);

Executing Raw SQL Queries

The query method in the QueryBuilder class is used to execute a raw SQL query. It takes a string argument representing the SQL query to be executed.

public function query(string $sql): self

Arguments Summary

Argument NameTypeDescription
$sqlstringThe SQL query string to be executed

Warning: Using raw SQL queries can expose your application to SQL Injection attacks. It's recommended to use prepared SQL queries for better security. See the next section for more details.

QueryBuilder::execute

The execute method is used to execute the query.

public function execute() : self

Examples

SELECT query with non-prepared SQL Db::query()

$queryBuilder->query("SELECT * FROM users WHERE name = 'John'")->execute();

UPDATE query with non-prepared SQL Db::query()

$queryBuilder->query("UPDATE users SET name = 'Jane' WHERE id = 1")->execute();

Executing Prepared SQL Queries

The query method also supports prepared SQL queries. This is achieved by using placeholders in the SQL query string and passing the actual values separately. The placeholders method is used to pass the actual values for the placeholders.

Arguments Summary

public function query(string $sql): self
public function placeholders(array $values): self
Argument NameArgument TypeDescriptionExamples
$sqlstringThe SQL query string with placeholders
'SELECT * FROM users WHERE name = :name'
'UPDATE users SET name = :newName WHERE id = :id'
$valuesarrayThe actual values for the placeholders
['name' => 'John Doe']
['newName' => 'Jane Doe', 'id' => 10]

Examples

SELECT query with prepared SQL Db::query()

$queryBuilder = new QueryBuilder();
$queryBuilder->query("SELECT * FROM users WHERE name = :name")
             ->placeholders(['name' => 'John'])->execute();

UPDATE query with prepared SQL Db::query()

$queryBuilder = new QueryBuilder();
$queryBuilder->query("UPDATE users SET name = :newName WHERE id = :id")
             ->placeholders(['newName' => 'Jane', 'id' => 1])->execute();