# Database Integration

PHPFast makes it easy to work with databases. It has a Database class and built-in Drivers that help you connect to your database using Models and a query builder.

The database settings are stored in `application/Config/Config.php`, where you can easily change and manage different database connections.

## Models

**Models** help you interact with the database easily. Each model represents a table in the database and provides methods to fetch, insert, update, and delete data.

By default, all models are stored in `application/Models/`.

## Creating a Model

* Go to `application/Models/`.
* Create a new file, e.g., `UsersModel.php`.
* Write the model code like this:

```php
<?php

namespace App\Models;

use System\Core\BaseModel;

class UsersModel extends BaseModel {
    protected $table     = 'users';                 // Connects to the 'users' table
    protected $fillable  = ['username', 'email'];   // Columns that can be changed
    protected $guarded   = ['id', 'created_at'];    // Columns that should NOT be modified

    public function _schema() {
        return [
            'id'       => ['type' => 'int unsigned', 'auto_increment' => true, 'key' => 'primary'],
            'username' => ['type' => 'varchar(100)', 'null' => false],
            'email'    => ['type' => 'varchar(150)', 'null' => false]
        ];
    }
    
    public function getUsers($where = '', $params = [], $orderBy = 'id DESC', $page = 1, $limit = null){
        return $this->list($this->table, $where, $params, $orderBy, $page, $limit);
    }
    
    // Additional methods for custom queries
}
```

## Changing the Database Driver

To switch between database drivers, update the `db_driver` setting in `application/Config/Config.php`

```php
'db' => [
    'db_driver'   => 'postgresql', // Change to 'mysql' or 'postgresql'
    'db_host'     => '127.0.0.1',
    'db_port'     => 5432,
    'db_username' => 'postgres',
    'db_password' => '',
    'db_database' => 'phpfast',
    'db_charset'  => 'utf8'
],
```

## Using a Model in a Controller

After creating a model, you can use it in a **controller** to interact with the database.

```php
<?php

use App\Models\UsersModel;

class UsersController extends BaseController {
    public function index() {
        $usersModel = new UsersModel(); // Load the model
        $users      = $usersModel->getUsers(); // Get all users from the database
        $this->render('users/index', ['users' => $users]); // Send data to the view
    }
}
```

## Managing Database Schema

Each model includes a `_schema()` method that defines the **structure of the database table** it represents.

You can synchronize the model schema with the database using the command-line tool:

```sh
php init table users
```

{% hint style="warning" %}
Important

When defining models, use these properties for secure and efficient database operations:

* **`$table`** → Defines which database table the model interacts with.
* **`$fillable`** → Lists columns that can be mass-assigned (used in insert/update).
* **`$guarded`** → Lists columns that **cannot** be mass-assigned for security.
  {% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cmsfullform.com/documents/libraries/database-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
