PHP code example of switon / db

1. Go to this page and download the library: Download switon/db library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

switon / db example snippets


use Switon\Core\Attribute\Autowired;
use Switon\Db\ClientInterface;

final class UserRepository
{
    #[Autowired] protected ClientInterface $db;

    public function find(int $id): ?array
    {
        $rows = $this->db->fetchAll(
            'SELECT * FROM [users] WHERE id = :id LIMIT 1',
            ['id' => $id],
        );

        return $rows[0] ?? null;
    }

    public function rename(int $id, string $name): void
    {
        $db = $this->db->getTransient('default');
        $db->begin();

        try {
            $db->executeUpdate(
                'UPDATE [users] SET name = :name WHERE id = :id',
                ['id' => $id, 'name' => $name],
            );
            $db->commit();
        } catch (\Throwable $e) {
            $db->rollback();
            throw $e;
        }
    }
}