PHP code example of hulotte / database

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

    

hulotte / database example snippets


$pdo = new \PDO(
    'mysql:host=<database_host>;dbname=<database_name>', 
    '<username>', 
    '<password>'
);

$database = new \Hulotte\Database\Database($pdo);

// Launch a "fetchAll" query
$results = $database->query('SELECT * FROM user WHERE id = 1');

// Launch a "fetchAll" query with prepare
$results = $database->prepare('SELECT * FROM user WHERE id = :id', [':id' => 1]);

// You can use same methods to launch a simple fetch by passing "true" to the last argument
$results = $database->query('SELECT * FROM user WHERE id = 1', null, true);
$results = $database->prepare('SELECT * FROM user WHERE id = :id', [':id' => 1], null, true)

// The requests which are not in "select" return an instance of PDOStatement
$result = $database->query('UPDATE test SET name = "Fifi" WHERE id = 1)');

// PDO's lastInsertId method is also accessible
$result = $database->getLastInsertId();

class UserEntity
{
    private int $id;
    
    private string $name;
    
    public function getId(): int
    {
        return $this->id;
    }
    
    public function setId(int $id): void
    {
        $this->id = $id;
    }
    
    public function getName(): string
    {
        return $this->name;
    }
    
    public function setName(string $name): void
    {
        $this->name = $name;
    }
}

class UserRepository extends \Hulotte\Database\Repository
{
    // Define the Entity class
    protected string $entity = UserEntity::class;
    
    // Define the table's name in database
    protected string $table = 'user';
}

$userRepository = new UserRepository($database);

// Get on user by is id
$result = $userRepository->find(1); // Return a UserEntity

// Get all the users
$results = $userRepository->all(); // Return an array of UserEntity

// Get the last insert id
$result = $userRepository->getLastInsertId();

// On the UserRepository class
public function findByName(string $name): userEntity
{
    $statement = 'SELECT * FROM ' . $this->table . ' WHERE name = :name';
    
    return $this->query(
        $statement, // Your query 
        [':name' => $name], // Send params call a prepared request
        true // Send true if you want only one result. Send nothing if you want many results
    );
}