Query Builder - Insert Update Delete

The QueryBuilder provides a robust platform for data fetching and conversion. Understand the key principles for effective data manipulation.

This page provides a comprehensive guide on how to use the QueryBuilder class for insert, update, and delete operations in your database. The guide includes practical code samples for each operation.

Table of Contents

  1. Loading the QueryBuilder Class
  2. Insert
  3. Update
  4. Delete

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);

Insert Records

Method Signature

public function insert(string $table, array $values) : self

Arguments Summary

Argument NameArgument TypeDescriptionExamples
$tablestringThe name of the table to insert records into.
'users'
$valuesarrayAn associative array of column names and their corresponding values.
['name' => 'John Doe', 'email' => 'john.doe@example.com']

QueryBuilder::execute

The execute method is used to execute the query.

public function execute() : self

Examples

$queryBuilder->insert('users', ['name' => 'John Doe', 'email' => 'john.doe@example.com'])->execute();

Update Records

Method Signature

public function update(string $table, array $values, array $where) : self

Arguments Summary

Argument NameArgument TypeDescriptionExamples
$tablestringThe name of the table to update records in.
'users'
$valuesarrayAn associative array of column names and their new values.
['name' => 'Jane Doe', 'status' => 'active']
$where?arrayAn array of SQL WHERE conditions
['status' => 'active']
['users.id' => 'profiles.user_id']
['users.id >' => 10]
['users.id >' => 10, 'users.username LIKE' => '%me%']

Examples of Use

$queryBuilder->update('users', ['name' => 'Jane Doe'], ['id' => 1])->execute();

Delete Records

Method Signature

public function delete(string $table, array $where) : self

Arguments Summary

Argument NameArgument TypeDescriptionExamples
$tablestringThe name of the table to delete records from.
'users'
$where?arrayAn array of SQL WHERE conditions
['status' => 'active']
['users.id' => 'profiles.user_id']
['users.id >' => 10]
['users.id >' => 10, 'users.username LIKE' => '%me%']

Examples

$queryBuilder->delete('users', ['id' => 1])->execute();