DownloadDatabase class and DatabaseTrait class CRUD Operations
Database class operations
Run raw Query
$db = new Database();
$results = $db->query(
    "SELECT * FROM articles WHERE status = ? AND author_id = ?",
    ['published', 42]
);
 
Insert record
$db = new Database();
$insertId = $db->insert('articles', [
    'title' => 'New Article',
    'content' => null, // Will insert as NULL
    'author_id' => 42,
]);
 
Update record
$db = new Database();
$db->update('articles', ['views' => 100, 'content' => null], ['id' => 5]);
 
Delete record
$db = new Database();
$db->delete('articles', ['id' => 5]);
 
Count Records
$db = new Database();
$total = $db->count('articles', 'id', ['author_id' => 42]);
 
DatabaseTrait class operations
Add DatabaseTrait to a class. This is for Classes that directly correlate to database records.
class ClassName {
    use DatabaseTrait;
    public int $id;
    public string $title = '';
    public string $content = '';
    /
     * Get object by id
     * @param int $id
     * @throws Exception
     */
    function __construct(int $id)
    {
        $db = new Database();
        $sql = "SELECT * FROM `" . self::getTable() . "` WHERE `" . self::getPrimaryField() . "` = ?";
        $record = $db->fetchRecord($sql, [$id]);
        if($record) {
            $this->id = $record->id;
            $this->title = $record->title;
            $this->content = $record->content;
        } else {
            throw new Exception('Record does not exist.');
        }
    }
    /
     * @return string
     */
    static function getPrimaryField(): string
    {
        return 'id';
    }
    /
     * @return string
     */
    static function getTable(): string
    {
        return 'tableName';
    }
    /
     * @param int $id
     * @return static
     * @throws ReflectionException
     */
    static function getObject(int $id): static
    {
        return new static($id);
    }
}
 
Insert new record
ClassName::insert([
    'title' => 'Breaking News!,
    'content' => 'content goes here!',
]);
 
Update a record
$object = ClassName::whereUnique(['id' => 1]);
$object->update([
    'title' => 'updated title',
]);
 
Select WHERE
$objects = ClassName::where([
	'title' => 'Breaking News!',
]);
 
Select WHERE LIKE (for searches)
$search = 'keyword';
$objects = ClassName::whereLike([
    'title' => $search,
    'content' => $search,
]);
 
Delete record
$object = ClassName::whereUnique(['id' => 1]);
$object->delete();
 
Select All
$objects = ClassName::all(['title' => 'asc']);
  |