PHP code example of piko / db-record

1. Go to this page and download the library: Download piko/db-record 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/ */

    

piko / db-record example snippets




use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class Contact extends DbRecord
{
    #[Column(primaryKey: true)]
    public ?int $id = null;

    #[Column]
    public ?string $firstname = null;

    #[Column]
    public ?string $lastname = null;

    #[Column]
    public ?bool $active = false;
}

use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class ContactMapped extends DbRecord
{
    #[Column(name: 'id', primaryKey: true)]
    public ?int $contactId = null;

    #[Column(name: 'firstname')]
    public ?string $firstName = null;

    #[Column(name: 'lastname')]
    public ?string $lastName = null;

    #[Column(name: 'active')]
    public ?bool $isActive = false;
}

use DateTimeImmutable;
use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class ContactAdvancedTypes extends DbRecord
{
    #[Column(primaryKey: true)]
    public ?int $id = null;

    #[Column(type: 'float')]
    public ?float $income = null;

    #[Column(name: 'name', type: 'json')]
    public ?array $nameData = null;

    #[Column(name: 'lastname', type: 'datetime_immutable')]
    public ?DateTimeImmutable $lastSeenAt = null;

    #[Column(name: 'firstname', type: 'decimal', scale: 4)]
    public ?string $balance = null;
}

use Piko\DbRecord;

class ContactStringPk extends DbRecord
{
    protected string $tableName = 'contact';
    protected string $primaryKey = 'firstname';

    protected array $schema = [
        'firstname' => self::TYPE_STRING,
        'lastname'  => self::TYPE_STRING,
    ];
}

$contact = new ContactStringPk($db);
$contact->firstname = 'pk_insert';
$contact->lastname = 'Doe';
$contact->save(); // INSERT with provided primary key

$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = <<<SQL
CREATE TABLE contact (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  firstname TEXT,
  lastname TEXT,
  active INTEGER DEFAULT 0
)
SQL;

$db->exec($query);

$contact = new Contact($db);
$contact->firstname = 'John';
$contact->lastname = 'Doe';
$contact->active = true;
$contact->save();

echo "Contact id: {$contact->id}"; // Contact id : 1

$contact = (new Contact($db))->load(1);

var_dump($contact->firstname); // John

$exists = (new Contact($db))->exists(1); // true

$contact->lastname = 'Doe Jr.';
$contact->save();

$contact->delete();