get()
public function get(string $order_by, string $table, string $order_direction = 'ASC', ?string $return_type = 'object'): array
Description
Fetches all records from a specified database table with optional ordering and return type. This method validates table existence, prevents SQL injection by validating column names, and supports both object and array return formats.
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| order_by | string | The column name to order results by. Must contain only alphanumeric characters and underscores. | - | Yes |
| table | string | The name of the database table to query. | - | Yes |
| order_direction | string | The sort direction: 'ASC' for ascending or 'DESC' for descending. | 'ASC' | No |
| return_type | string|null | The return format: 'object' for objects, 'array' for associative arrays, or null for empty array. | 'object' | No |
Return Value
| Type | Description |
|---|---|
| array | An array of objects or associative arrays representing the fetched rows. Returns empty array if return_type is null. |
Exceptions
- RuntimeException - If the specified table does not exist in the database.
- InvalidArgumentException - If order_direction is not 'ASC' or 'DESC', or if order_by contains invalid characters.
Example #1
The code sample below demonstrates how to retrieve all users from the 'users' table, ordered by 'id' in ascending order (default).
Example #2
The code sample below demonstrates how to retrieve all products from the 'products' table, ordered by 'price' in descending order.
Example #3
The code sample below demonstrates how to retrieve all orders from the 'orders' table, ordered by 'created_at' in ascending order, returning results as associative arrays instead of objects.
Important Notes
- Both
$order_byand$tableparameters are required. - The method validates that the table exists before executing the query.
- Column names are validated to prevent SQL injection attacks.
- When
$return_typeis set to 'object', results are returned as objects (PDO::FETCH_OBJ). - When
$return_typeis set to 'array', results are returned as associative arrays (PDO::FETCH_ASSOC). - If
$return_typeis null, an empty array is returned.