1. Go to this page and download the library: Download popphp/pop-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/ */
use Pop\Db\Db;
use Pop\Db\Record;
$db = Db::mysqlConnect([
'database' => 'DATABASE',
'username' => 'DB_USER',
'password' => 'DB_PASS'
]);
class Users extends Record {}
Record::setDb($db);
use Pop\Db\Db;
use Pop\Db\Record;
$db = Db::mysqlConnect([
'database' => 'DATABASE',
'username' => 'DB_USER',
'password' => 'DB_PASS'
]);
$dbUsers = Db::mysqlConnect([
'database' => 'DATABASE_FOR_USERS',
'username' => 'DB_USER',
'password' => 'DB_PASS'
]);
class Users extends Record {};
Users::setDb($dbUsers); // Only the users table class uses the $dbUsers connection
Record::setDb($db); // All other table classes will use the $db connection
class Users extends Record
{
protected ?string $table = 'users';
// Allowlist: only these columns can be mass-assigned
protected array $fillable = ['username', 'email'];
}
class Users extends Record
{
protected ?string $table = 'users';
// Denylist: everything except these columns can be mass-assigned
protected array $guarded = ['is_admin', 'role'];
}
$user = new Users($request->all()); // filtered through $fillable/$guarded
$user->save();
$user = Users::findById(1);
$user->fill($request->all()); // filtered through $fillable/$guarded
$user->save(); // updates the existing row
$user->isFillable('role'); // false, if 'role' is guarded or not in $fillable
// Fetch a single user record by ID
$user = Users::findById(1);
// Search for a single user record
$user = Users::findOne(['username' => 'testuser']);
// Search for a single user record, or create one if it doesn't exist
$user = Users::findOneOrCreate(['username' => 'testuser']);
// Search for the latest single user record
$user = Users::findLatest();
$criteria = Users::predicate()->equalTo('username', 'testuser')->equalTo('email', '[email protected]');
$user = Users::findOneOrCreate($criteria); // creates ['username' => 'testuser', 'email' => '[email protected]'] if not found
// Search for the latest single user record by 'last_login'
$user = Users::findLatest('last_login');
$user->username = 'newusername';
$user->save();
$user->delete();
$user->increment('attempts'); // Increment column by one and save
$user->decrement('capacity', 5); // Decrement column by 5 and save
$user->reset('attempts'); // Reset column to null and save
$user->reset('attempts', 0); // Reset column to a given value (e.g. 0 or '') and save
// Make a new copy of the user record in the database
// The $replace parameter can be an array of new, overriding column values
$newUser = $user->copy($replace);
class Users extends Pop\Db\Record
{
protected function beforeSave(): void
{
$this->updated_at = date('Y-m-d H:i:s');
}
protected function afterDelete(): void
{
Logger::info('User deleted', ['id' => $this->id]);
}
}
$user = Users::findOne(['username' => 'testuser']);
if ($user->verify('password', $attemptedPassword)) {
// The user submitted the correct password.
}
if ($user->verify('password', $attemptedPassword)) {
if ($user->needsRehash()) {
$user->rehash('password', $attemptedPassword); // re-hashes with current $hashOptions and saves
}
// proceed as authenticated
}
use Pop\Db\Record\Auth;
class Users extends Auth
{
// No $hashFields needed - Auth::__construct() always adds $passwordField to it for you
}
$user = new Users();
// $mfa = false: authenticate outright, no MFA step
if ($user->authenticate($username, $attemptedPassword, false)) {
// Logged in
} else {
echo $user->getAuthFailureMessage();
}
// $mfa = true (the default): on success, a fresh MFA code + expiration are generated,
// saved to the user record, and the record itself is returned so the app can send the
// code however it likes (email, SMS, etc.)
$result = $user->authenticate($username, $attemptedPassword);
if ($result !== false) {
// $result is the user record - send $result->mfa_code to the user
} else {
echo $user->getAuthFailureMessage();
}
$user = Users::findOne(['username' => $username]);
if ($user->authenticateMfa($attemptedCode)) {
// MFA passed - the stored code is cleared, so it cannot be reused
} else {
echo $user->getAuthFailureMessage(); // INVALID_MFA_CODE, MFA_CODE_EXPIRED, etc.
}
$users = Users::findBy(['id' => 1]); // WHERE id = 1
$users = Users::findBy(['id!=' => 1]); // WHERE id != 1
$users = Users::findBy(['id>' => 1]); // WHERE id > 1
$users = Users::findBy(['id>=' => 1]); // WHERE id >= 1
$users = Users::findBy(['id<' => 1]); // WHERE id < 1
$users = Users::findBy(['id<=' => 1]); // WHERE id <= 1
$users = Users::findBy(['%username%' => 'test']); // WHERE username LIKE '%test%'
$users = Users::findBy(['username%' => 'test']); // WHERE username LIKE 'test%'
$users = Users::findBy(['%username' => 'test']); // WHERE username LIKE '%test'
$users = Users::findBy(['-%username' => 'test']); // WHERE username NOT LIKE '%test'
$users = Users::findBy(['username%-' => 'test']); // WHERE username NOT LIKE 'test%'
$users = Users::findBy(['-%username%-' => 'test']); // WHERE username NOT LIKE '%test%'
$users = Users::findBy(['username' => null]); // WHERE username IS NULL
$users = Users::findBy(['username-' => null]); // WHERE username IS NOT NULL
$users = Users::findBy(['id' => [2, 3]]); // WHERE id IN (2, 3)
$users = Users::findBy(['id-' => [2, 3]]); // WHERE id NOT IN (2, 3)
$users = Users::findBy(['id' => '(1, 5)']); // WHERE id BETWEEN (1, 5)
$users = Users::findBy(['id-' => '(1, 5)']); // WHERE id NOT BETWEEN (1, 5)
class Users extends Pop\Db\Record
{
/**
* Mock Schema
* - id
* - role_id (FK to roles.id)
* - username
* - password
* - email
*/
// Define the 1:1 relationship of the user's role
public function role(?array $options = null, bool $eager = false)
{
return $this->hasOneOf('Roles', 'role_id', $options, $eager);
}
// Define the 1:1 relationship of the info record this user owns
public function info(?array $options = null, bool $eager = false)
{
return $this->hasOne('Info', 'user_id', $options, $eager);
}
// Define the 1:many relationship to all the orders this user owns
public function orders(?array $options = null, bool $eager = false)
{
return $this->hasMany('Orders', 'user_id', $options, $eager);
}
}
class Roles extends Pop\Db\Record
{
/**
* Mock Schema
* - id (FK to users.role_id)
* - role
*/
}
class Info extends Pop\Db\Record
{
/**
* Mock Schema
* - user_id (FK to users.id)
* - address
* - phone
*/
// Define the parent relationship up to the user that owns this info record
public function user(?array $options = null, bool $eager = false)
{
return $this->belongsTo('Users', 'user_id', $options, $eager);
}
}
class Orders extends Pop\Db\Record
{
/**
* Mock Schema
* - id
* - user_id (FK to users.id)
* - order_date
* - order_total
* - products
*/
// Define the parent relationship up to the user that owns this order record
public function user(?array $options = null, bool $eager = false)
{
return $this->belongsTo('Users', 'user_id', $options, $eager);
}
}
// The two 1:1 relationships
$user = Users::findById(1);
print_r($user->role()->toArray());
print_r($user->info()->toArray());
$user = Users::with(['info', 'orders'])->getOne(['id' => 1]);
var_dump($user->info); // NULL -- a 1:1 relationship with no match
echo count($user->orders); // 0 -- a 1:many relationship is an empty collection
class Orders extends Pop\Db\Record
{
/**
* Mock Schema
* - id
* - user_id (FK to users.id)
* - org_id (FK to users.org_id)
* - order_date
* - order_total
* - products
*/
// Define the parent relationship up to the user that owns this order record,
// matched on both `user_id` and `org_id`
public function user(?array $options = null, bool $eager = false)
{
return $this->belongsTo('Users', ['user_id', 'org_id'], $options, $eager);
}
}
php
use Pop\Db\Sql\Migrator;
Migrator::create('MyNewMigration', __DIR__ . 'migrations');
php
use Pop\Db\Sql\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
public function up()
{
}
public function down()
{
}
}
php
use Pop\Db\Sql\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
public function up()
{
$schema = $this->db->createSchema();
$schema->create('users')
->int('id', 16)->increment()
->varchar('username', 255)
->varchar('password', 255)
->primary('id');
$schema->execute();
}
public function down()
{
$schema = $this->db->createSchema();
$schema->drop('users');
$schema->execute();
}
}
php
use Pop\Db\Adapter\AbstractAdapter;
use Pop\Db\Sql\Seeder\AbstractSeeder;
class MyFirstSeeder extends AbstractSeeder
{
public function run(AbstractAdapter $db): void
{
}
}