1. Go to this page and download the library: Download irfantoor/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/ */
# a database object is created, but it needs to be connected to a database
# before querring
$db = new Database();
# for sql
$connection = [
'type' => 'sqlite',
'file' => 'storage_path/users.sqlite',
];
# for mysql
$connection = [
'type' => 'mysql',
'host' => 'localhost',
'user' => 'root',
'password' => 'toor',
'db_name' => 'test',
];
$db->connect($connection);
# Note: the definition of 'type' in connection is obligatory.
$result = $db->query('SECLECT count(*) from users where valid=true');
$db->insert('users', ['name' => 'Fabien Potencier', 'email' => '[email protected]']);
# OR
$user = [
'name' => 'Irfan TOOR',
'email' => '[email protected]',
'password' => 'its-a-test',
];
$db->insert('users', $user);
# NOTE: the query will be prepared and values will be bound automatically
namespace Models\Users;
use IrfanTOOR\Database\Model;
class Users extends Model
{
function __construct($connection)
{
# schema needs to be defined
$this->schema = [
'id' => 'INTEGER PRIMARY KEY',
'name' => 'NOT NULL',
'email' => 'COLLATE NOCASE',
'password' => 'NOT NULL',
'token',
'validated' => 'BOOL DEFAULT false',
'created_on' => 'DATETIME DEFAULT CURRENT_TIMESTAMP',
'updated_on' => 'INTEGER'
];
# indices need to be defined
$this->indices = [
['index' => 'name'],
['unique' => 'email'],
];
# call the constructor with the $connection
parent::__construct($connection);
}
}
use Model\Users;
$connection = [
'file' => $db_path . 'users.sqlite',
'table' => 'users'
];
# NOTE: If table name is not provided Model name e.g. 'Users' will be converted
# to lowercase i.e. 'users' and will be used as table name.
$users = new Users($connection);
$file = $users->getDatabaseFile();
$schema = $users->prepareSchema();
echo $schema;
$file = $sb_path . 'users.sqlite';
# create a file and deploy the schema if it does not exist
if (!file_exists($file)) {
file_put_contents($file, '');
$users = new Users(['file' => $file]);
$schema = $users->prepareSchema();
$users->deploySchema($schema);
}
$user['password'] = 'password-to-be-updated';
$users->insertOrUpdate($user); # updates the record of previous example
$user = [
'name' => 'Some User',
'email' => '[email protected]',
'password' => 'some-password',
];
$users->insertOrUpdate($user); # inserts the record now
$email = '[email protected]';
$users->update(
# only the record data which we need to modify
[
'password' => 'password',
],
# options
[
'where' => 'email = :email',
'bind' => [
'email' => $email
]
]
);